Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit f1f6e7b

Browse files
authored
Update 0199-binary-tree-right-side-view.cs
1 parent 1f4fb25 commit f1f6e7b

File tree

1 file changed

+14
-29
lines changed

1 file changed

+14
-29
lines changed

csharp/0199-binary-tree-right-side-view.cs

Lines changed: 14 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -12,34 +12,19 @@
1212
* }
1313
*/
1414
public class Solution {
15+
private List<int> _result = new();
16+
1517
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;
18+
Dfs(root, 0);
19+
return _result;
4420
}
45-
}
21+
22+
private void Dfs(TreeNode root, int level) {
23+
if (root == null) return;
24+
if (level >= _result.Count) _result.Add(root.val);
25+
26+
// At first visit right node
27+
Dfs(root.right, level + 1);
28+
Dfs(root.left, level + 1);
29+
}
30+
}

0 commit comments

Comments
 (0)