0199. Binary Tree Right Side View

199. Binary Tree Right Side View #

题目 #

给定一个二叉树的 根节点 root,按照从顶部到底部的顺序,返回从右侧所能看到的节点值。

思路 #

代码 #

public class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode() {}
    TreeNode(int val) { this.val = val; }
    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}
class Solution {
    public List<Integer> rightSideView(TreeNode root) {
        List<Integer> ans = new LinkedList<>();
        if (root == null) return ans;
        
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        
        while (queue.size() != 0) {
            int layerSize = queue.size();
            TreeNode node = null
                for (int i = 0; i < layerSize; i++) {
                    node = queue.poll();
                    
                    if (node.left != null) queue.offer(node.left);
                    if (node.right != null) queue.offer(node.right);
                }
            ans.add(node.val);
        }
        
        return ans;
    }
}