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:

/**
 * 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<Integer> rightSideView(TreeNode root) {
        List<Integer> ans = new ArrayList<>();
        if(root==null) return ans;
        List<TreeNode> list = new ArrayList<>();
        list.add(root);
        while(!list.isEmpty()){
            ans.add(list.get(list.size()-1).val);
            List<TreeNode> tmp = new ArrayList<>();
            for(int i=0; i<list.size(); i++){
                TreeNode tn = list.get(i);
                if(tn.left!=null) tmp.add(tn.left);
                if(tn.right!=null) tmp.add(tn.right);
            }
            list = tmp;
        }
        return ans;
    }
}
comments powered by Disqus