天天看點

【LeetCode】Binary Tree Right Side View 解題報告

【題目】

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]

.

【解析】

題意:給定一棵二叉樹,傳回從右邊看這棵二叉樹所看到的節點序列(從上到下)。

思路:層次周遊法。周遊到每層最後一個節點時,把其放到結果集中。

【Java代碼】

public class Solution {
    public List<Integer> rightSideView(TreeNode root) {
        List<Integer> ans = new ArrayList<Integer>();
        if (root == null) return ans;
        
        LinkedList<TreeNode> queue = new LinkedList<TreeNode>();
        queue.add(root);
        queue.add(null);
        
        while (!queue.isEmpty()) {
            TreeNode node = queue.pollFirst();
            
            if (node == null) {
                if (queue.isEmpty()) {
                    break;
                } else {
                    queue.add(null);
                }
            } else {
                // add the rightest to the answer
                if (queue.peek() == null) {
                    ans.add(node.val);
                }
                
                if (node.left != null) {
                    queue.add(node.left);
                }
                if (node.right != null) {
                    queue.add(node.right);
                }
            }
        }
        
        return ans;
    }
}
           

繼續閱讀