leetcode 199 Binary Tree Right Side View
z

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:

1
2
3
4
5
6
7
8
9
Input: [1,2,3,null,5,null,4]
Output: [1, 3, 4]
Explanation:

1 <---
/ \
2 3 <---
\ \
5 4 <---

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
/**
* 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<Integer> ans = new ArrayList<>();
helper(ans, root, 0);
return ans;
}
public void helper(List<Integer> ans, TreeNode root, int level) {
if (root == null)
return ;
if (ans.size() == level) {
ans.add(root.val);
}
if (root.right != null)
helper(ans, root.right, level+1);
if (root.left != null)
helper(ans, root.left, level+1);
}
}