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

Example:

Input: [1,2,3,null,5,null,4]
Output: [1, 3, 4]
Explanation:

   1            <---
 /   \
2     3         <---
 \     \
  5     4       <---
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List<Integer> rightSideView(TreeNode root) {
        List<List<Integer>> list = new ArrayList();
        List<Integer> res = new ArrayList();
        Helper(0, list, root);
        int l = list.size();
        for(int i = 0; i < l; i++){
            List<Integer> tmp = list.get(i);
            res.add(tmp.get(tmp.size()-1));
            
        }
        return res;
    }
    public void Helper(int height, List<List<Integer>> list, TreeNode p){
        if(p == null) return;
        if(height == list.size()){
            list.add(new ArrayList());
        }
        list.get(height).add(p.val);
        Helper(height+1, list, p.left);
        Helper(height+1, list, p.right);
    }
}

还是基于level order view。得到每一层,再把每个数组最后一项拿出来即可。

 

class Solution {
    public List<Integer> rightSideView(TreeNode root) {       
        List<Integer> res = new ArrayList();
        if(root == null) return res;  
        help(res, 0, root);       
        return res;
    }
    public void help(List<Integer> res, int h, TreeNode root) {
        if(root == null) return;
        if(res.size() == h) res.add(root.val);
        help(res, h + 1, root.right);
        help(res, h + 1, root.left);
    }
}

不用level order也可以,每一层只选取一个元素,先选right,如果有就放进去,没有就只能退而求其次选left了。

posted @ 2019-08-28 02:10  Schwifty  阅读(130)  评论(0编辑  收藏  举报