-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathBinaryTreeRightSideView.java
42 lines (35 loc) · 1.12 KB
/
BinaryTreeRightSideView.java
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
package com.smlnskgmail.jaman.leetcodejava.medium;
import com.smlnskgmail.jaman.leetcodejava.support.TreeNode;
import java.util.*;
// https://leetcode.com/problems/binary-tree-right-side-view/
public class BinaryTreeRightSideView {
private final TreeNode input;
public BinaryTreeRightSideView(TreeNode input) {
this.input = input;
}
public List<Integer> solution() {
if (input == null) {
return Collections.emptyList();
}
List<Integer> result = new ArrayList<>();
Deque<TreeNode> deque = new LinkedList<>();
deque.add(input);
while (!deque.isEmpty()) {
int size = deque.size();
while (size != 0) {
TreeNode node = deque.poll();
if (node.left != null) {
deque.addLast(node.left);
}
if (node.right != null) {
deque.addLast(node.right);
}
if (size == 1) {
result.add(node.val);
}
size--;
}
}
return result;
}
}