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。得到每一层,再把每个数组最后一项拿出来即可。

原文地址:https://www.cnblogs.com/wentiliangkaihua/p/11421681.html