Thanks to visit codestin.com Credit goes to github.com
We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent 7144043 commit 4c9fd50Copy full SHA for 4c9fd50
java/104-Maximum-Depth-of-Binary-Tree.java
@@ -1,7 +1,27 @@
1
+// Recursive DFS
2
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
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