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]
.
public List<Integer> rightSideView(TreeNode root) {
Set<Integer> visited = new HashSet<Integer>();
List<Integer> result = new ArrayList<Integer>();
helper(result, visited, root, 1);
return result;
}
void helper(List<Integer> result, Set<Integer> visited, TreeNode root, int level) {
if (root == null) {
return;
}
if (!visited.contains(level)) {
result.add(root.val);
visited.add(level);
}
helper(result, visited, root.right, level+1);
helper(result, visited, root.left, level+1);
}