[leetcode] problem 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
4
5
   1            <---
/
2 3 <---

5 4 <---

Code

1
2
3
4
5
6
public class  {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
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
public List<Integer> rightSideView(TreeNode root) {
List<Integer> result = new ArrayList<>();

if (root == null)
return result;

LinkedList<TreeNode> queue = new LinkedList<>();
queue.offer(root);

while (!queue.isEmpty()) {
int size = queue.size();
result.add(queue.peekLast().val);

for (int i = 0; i < size; i++) {
TreeNode node = queue.poll();

if (node.left != null)
queue.offer(node.left);

if (node.right != null)
queue.offer(node.right);
}
}

return result;
}