Skip to content

Commit ff18c5b

Browse files
author
Li Li
committed
add BFS recursion version for 104
1 parent 7e68ede commit ff18c5b

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
// recursion
2+
public class Solution {
3+
public int MaxDepth(TreeNode root) {
4+
if (root == null) return 0;
5+
return 1 + Math.Max(MaxDepth(root.left), MaxDepth(root.right));
6+
}
7+
}
8+
9+
// BFS interation
10+
public class SolutionBFS {
11+
public int MaxDepth(TreeNode root) {
12+
if (root == null) return 0;
13+
Queue<TreeNode> q = new Queue<TreeNode>();
14+
q.Enqueue(root);
15+
int maxDepth = 0;
16+
while (q.Count > 0) {
17+
int size = q.Count;
18+
while (size-- > 0) {
19+
TreeNode node = q.Dequeue();
20+
if (node.left != null) q.Enqueue(node.left);
21+
if (node.right != null) q.Enqueue(node.right);
22+
}
23+
maxDepth++;
24+
}
25+
return maxDepth;
26+
}
27+
}

0 commit comments

Comments
 (0)