问题:
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;
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。