leetcode 199. 二叉树的右视图

本文介绍了一种算法,用于解决从右视角观察二叉树并返回顶部到底部节点值的问题。通过广度优先搜索(BFS),确保每一层最右侧节点优先处理,从而收集到从右侧看到的节点值。

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

给定一棵二叉树,想象自己站在它的右侧,按照从顶部到底部的顺序,返回从右侧所能看到的节点值。

示例:

输入: [1,2,3,null,5,null,4]
输出: [1, 3, 4]

挺好的题目,注意到同一高度的节点,从右边看必定只能看到最右边的节点,这是这个题的关键。

那么我们只要保证在bfs的时候,同一高度的点最右边的可以先出队,每次当出队的点高度没出现过时,就把这个节点加入答案数组即可。

为保证同一高度的点最右边先出队,那么最右边点就需要先入队,只要我们层序遍历时让右子树先入队即可。

其他就是简单的bfs,详见代码。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
 class tree
 {
     TreeNode root;
     int depth;
     public tree(TreeNode root,int depth)
     {
         this.root = root;
         this.depth = depth;
     }
 }
class Solution {
    int Max = 100010;
    public List<Integer> rightSideView(TreeNode root) {
        Queue<tree>q = new LinkedList<tree>();
        ArrayList<Integer>ans = new ArrayList<Integer>();
        if(root==null)
            return ans;
        int vis[] = new int [Max];
        q.offer(new tree(root,1));
        while(q.size()>0)
        {
            tree now = q.poll();
            if(vis[now.depth]==0)
            {
                vis[now.depth] = 1;
                ans.add(now.root.val);
            }
            if(now.root.right!=null)
                q.offer(new tree(now.root.right,now.depth+1));
            if(now.root.left!=null)
                q.offer(new tree(now.root.left,now.depth+1));
        }
        return ans;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值