199-Binary Tree Right Side View

本文介绍了一种从右视图角度获取二叉树节点值的算法实现,通过两种方法——宽度优先搜索(BFS)和深度优先搜索(DFS)进行讲解。提供了详细的代码示例及解析。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Description

Given a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom.


Example:

Input: [1,2,3,null,5,null,4]
Output: [1, 3, 4]
Explanation:

   1            <---
 /   \
2     3         <---
 \     \
  5     4       <---

问题描述

给定二叉树, 返回以从右边看的视角所能获取到的值。


问题分析

BFS或者DFS

DFS使用前序遍历(与一般的前序遍历的不同的地方为先从右边遍历), 另外注意利用height


解法1

public class Solution {
    public List<Integer> rightSideView(TreeNode root) {
        // reverse level traversal
        List<Integer> result = new ArrayList();
        if(root == null) return result;

        Queue<TreeNode> queue = new LinkedList();
        queue.offer(root);
        while (queue.size() != 0) {
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                TreeNode cur = queue.poll();
                if (i == 0) result.add(cur.val);
                if (cur.right != null) queue.offer(cur.right);
                if (cur.left != null) queue.offer(cur.left);
            }

        }

        return result;
    }
}

解法2

class Solution {
    public List<Integer> rightSideView(TreeNode root) {
        List<Integer> res = new ArrayList();
        if(root == null) return res;

        preorder(root, res, 0);
        return res;
    }
    public void preorder(TreeNode root, List<Integer> res, int height){
        if(root == null) return;

        if(height == res.size())    res.add(root.val);

        preorder(root.right, res, height + 1);
        preorder(root.left, res, height + 1);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值