Skip to content

Commit 6442da7

Browse files
committed
Create 199-Binary-Tree-Right-Side-View.cs
1 parent d8989b2 commit 6442da7

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* public class TreeNode {
4+
* public int val;
5+
* public TreeNode left;
6+
* public TreeNode right;
7+
* public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) {
8+
* this.val = val;
9+
* this.left = left;
10+
* this.right = right;
11+
* }
12+
* }
13+
*/
14+
public class Solution {
15+
public IList<int> RightSideView(TreeNode root) {
16+
var result = new List<int>();
17+
if(root == null)
18+
return result;
19+
var q = new Queue<TreeNode>();
20+
q.Enqueue(root);
21+
22+
// traverse the tree using BFS
23+
while(true) {
24+
var count = q.Count;
25+
if(count == 0) break;
26+
27+
for(var i = 0; i < count; i++) {
28+
var cur = q. Dequeue();
29+
30+
if(cur.left != null)
31+
q.Enqueue(cur.left);
32+
if(cur.right != null)
33+
q.Enqueue(cur.right);
34+
35+
36+
// only add the last node from each level, i.e the rightmost node
37+
if(i == count - 1) {
38+
result.Add(cur.val);
39+
}
40+
}
41+
}
42+
43+
return result;
44+
}
45+
}

0 commit comments

Comments
 (0)