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

Skip to content

Commit 4c9fd50

Browse files
committed
Update 104-Maximum-Depth-of-Binary-Tree.java
1 parent 7144043 commit 4c9fd50

File tree

1 file changed

+21
-1
lines changed

1 file changed

+21
-1
lines changed
Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,27 @@
1+
// Recursive DFS
12
class Solution {
2-
33
public int maxDepth(TreeNode root) {
44
if (root == null) return 0;
55
return 1 + Math.max(maxDepth(root.left), maxDepth(root.right));
66
}
77
}
8+
9+
// BFS
10+
class Solution {
11+
public int maxDepth(TreeNode root) {
12+
if (root == null) return 0;
13+
Queue<TreeNode> queue = new LinkedList<>();
14+
queue.add(root);
15+
int levels = 0;
16+
while (!queue.isEmpty()) {
17+
int size = queue.size();
18+
for (int i = 0; i < size; i++) {
19+
TreeNode current = queue.poll();
20+
if (current.left != null) queue.add(current.left);
21+
if (current.right != null) queue.add(current.right);
22+
}
23+
levels++;
24+
}
25+
return levels;
26+
}
27+
}

0 commit comments

Comments
 (0)