Skip to content

Commit 9efe879

Browse files
add: Maximum depth of binary tree
1 parent 13adfec commit 9efe879

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
import java.util.LinkedList;
2+
import java.util.Queue;
3+
4+
// 시간복잡도 O(n)
5+
class Solution {
6+
public int depth = 0;
7+
public int maxDepth(TreeNode root) {
8+
9+
if(root == null) {
10+
return depth;
11+
}
12+
13+
Queue<TreeNode> q = new LinkedList<>();
14+
q.add(root);
15+
16+
while(!q.isEmpty()) {
17+
int size = q.size();
18+
depth++;
19+
20+
for(int i = 0; i < size; i++) {
21+
TreeNode p = q.poll();
22+
23+
if(p.right != null) {
24+
q.add(p.right);
25+
}
26+
27+
if(p.left != null) {
28+
q.add(p.left);
29+
}
30+
}
31+
}
32+
33+
return depth;
34+
}
35+
}

0 commit comments

Comments
 (0)