问题:
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].

解答:
核心思想是每一层只取一个结点,所以result的大小与高度是一样的。

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

guoluona
199 声望14 粉丝