leetcode199题 二叉树的右视图(广度优先遍历)√

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/m0_37719047/article/details/102622882

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

示例:

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

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

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List<Integer> rightSideView(TreeNode root) {
        List<Integer> ret=new ArrayList<Integer>();
        if(root==null) return ret;
        LinkedList<TreeNode> queue=new LinkedList<TreeNode>();
        queue.add(root);
        while(queue.size()!=0){
            int size=queue.size();
            for(int i=1;i<=size;i++){
                TreeNode node=queue.removeFirst();
                if(node.left!=null){
                    queue.addLast(node.left);
                }
                if(node.right!=null){
                    queue.addLast(node.right);
                }
                if(i==size) ret.add(node.val);
            }
        }
        return ret;
    }
}

猜你喜欢

转载自blog.csdn.net/m0_37719047/article/details/102622882