Skip to content

Commit 1908bf5

Browse files
committed
Added problem 199
1 parent dd37580 commit 1908bf5

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
// id: 199
2+
// Name: Binary Tree Right Side View
3+
// link: https://leetcode.com/problems/binary-tree-right-side-view/
4+
// Difficulty: Medium
5+
6+
class Solution {
7+
public List<Integer> rightSideView(TreeNode root) {
8+
// right side view means the rightmost element of each level
9+
10+
List<Integer> result = new ArrayList<>();
11+
12+
Queue<TreeNode> q = new LinkedList<>();
13+
if (root != null) {
14+
q.add(root);
15+
}
16+
17+
while (!q.isEmpty()) {
18+
int count = q.size();
19+
// traverse the complete level
20+
while (count > 0) {
21+
root = q.poll();
22+
23+
if (root.left != null) {
24+
q.add(root.left);
25+
}
26+
if (root.right != null) {
27+
q.add(root.right);
28+
}
29+
count--;
30+
}
31+
// add the last level to the result
32+
result.add(root.val);
33+
}
34+
35+
return result;
36+
}
37+
}

0 commit comments

Comments
 (0)