199. Binary Tree Right Side View

Medium
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.

For example:
Given the following binary tree,

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

You should return [1, 3, 4].

这道题居然一开始错用Stack来做了。来,跟我一起念:
BFS用Queue!BFS用Queue! BFS用Queue!
重要的事情说三遍!
接下来就跟Binary Level Order Traversal没什么两样了,只是每遍历完一层,要往res里添加该层最右边的节点值。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List rightSideView(TreeNode root) {
        List res = new ArrayList<>();
        if (root == null){
            return res;
        }              
        Queue queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()){
            int size = queue.size();
            List level = new ArrayList<>();
            for (int i = 0; i < size; i++){
                TreeNode node = queue.poll();
                level.add(node.val);
                if (node.left != null){
                    queue.offer(node.left);
                }
                if (node.right != null){
                    queue.offer(node.right);
                }
            }
            res.add(level.get(level.size() - 1));
        }
        return res;
        
    }
}

你可能感兴趣的:(199. Binary Tree Right Side View)