Skip to content

Commit 94a952d

Browse files
committed
feat: maximum-depth-of-binary-tree
1 parent cd799c5 commit 94a952d

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
/**
2+
* <a href="https://leetcode.com/problems/maximum-depth-of-binary-tree/">week4-2.maximum-depth-of-binary-tree</a>
3+
* <li>Description: Given the root of a binary tree, return its maximum depth.</li>
4+
* <li>Topics: Tree, Depth-First Search, Breadth-First Search, Binary Tree</li>
5+
* <li>Time Complexity: O(N), Runtime 1ms</li>
6+
* <li>Space Complexity: O(W), Memory 43.21MB</li>
7+
*/
8+
9+
class Solution {
10+
public int maxDepth(TreeNode root) {
11+
if (root == null) return 0;
12+
13+
Queue<TreeNode> queue = new LinkedList<>();
14+
queue.offer(root);
15+
16+
int depth = 0;
17+
while (!queue.isEmpty()) {
18+
depth++;
19+
int size = queue.size();
20+
for (int i = 0; i < size; i++) {
21+
TreeNode node = queue.poll();
22+
if (node.left != null) queue.offer(node.left);
23+
if (node.right != null) queue.offer(node.right);
24+
}
25+
}
26+
return depth;
27+
}
28+
}

0 commit comments

Comments
 (0)