LeetCode link

first thought

  • DFS.

solution1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public class Solution {
public List<Integer> rightSideView(TreeNode root) {
ArrayList<Integer> result = new ArrayList<>();
this.rightSideView(root, 0, result);
return result;
}
private void rightSideView(TreeNode node, int level, ArrayList<Integer> result) {
if (node == null) {
return;
}
if (result.size() <= level) {
result.add(node.val);
this.rightSideView(node.left, level + 1, result);
this.rightSideView(node.right, level + 1, result);
}
else {
result.set(level, node.val);
this.rightSideView(node.left, level + 1, result);
this.rightSideView(node.right, level + 1, result);
}
}
}

solution2

BFS

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
class Solution {
public List<Integer> rightSideView(TreeNode root) {
List<Integer> result = new ArrayList<>();
if (root == null) {
return result;
}
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
while (!queue.isEmpty()) {
Queue<TreeNode> queue2 = new LinkedList<>();
TreeNode lastNode = queue.peek();
while (!queue.isEmpty()) {
lastNode = queue.poll();
if (lastNode.left != null) {
queue2.add(lastNode.left);
}
if (lastNode.right != null) {
queue2.add(lastNode.right);
}
}
result.add(lastNode.val);
queue = queue2;
}
return result;
}
}