Thursday, October 15, 2015

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].
Solution
用一个queue来保存每一行的node, 把最右边的node.val存入到结果里。
Run time complexity is O(n), space complexity is O(n).
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public List rightSideView(TreeNode root) {
        List res = new ArrayList();
        if (root == null) {
            return res;
        }
        
        LinkedList queue = new LinkedList();
        queue.add(root);

        while (!queue.isEmpty()) {
            int size = queue.size();
            
            for (int i = 0; i < size; i++) {
                TreeNode top = queue.remove();
                
                if (i == 0) {  // the right-most node of the tree
                    res.add(top.val);
                }
                
                if (top.right != null) {
                    queue.add(top.right);
                }
                
                if (top.left != null) {
                    queue.add(top.left);
                }
            }
        }
        
        return res;
    }
}

No comments:

Post a Comment