Skip to content

Commit 0051f10

Browse files
committed
maximum-depth-of-binary-tree
1 parent 987da6f commit 0051f10

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
import java.util.*;
2+
3+
/**
4+
* Definition for a binary tree node.
5+
* public class TreeNode {
6+
* int val;
7+
* TreeNode left;
8+
* TreeNode right;
9+
* TreeNode() {}
10+
* TreeNode(int val) { this.val = val; }
11+
* TreeNode(int val, TreeNode left, TreeNode right) {
12+
* this.val = val;
13+
* this.left = left;
14+
* this.right = right;
15+
* }
16+
* }
17+
*/
18+
class Solution {
19+
class Data{
20+
TreeNode node;
21+
int depth;
22+
public Data(TreeNode node, int depth){
23+
this.node = node;
24+
this.depth = depth;
25+
}
26+
}
27+
public int maxDepth(TreeNode root) {
28+
return bfs(root);
29+
}
30+
public int bfs(TreeNode root) {
31+
int depth = 0;
32+
Queue<Data> q = new ArrayDeque<>();
33+
if (root != null){
34+
q.add(new Data(root, 1));
35+
}
36+
while (!q.isEmpty()){
37+
Data cur = q.poll();
38+
if (cur.depth > depth){
39+
depth = cur.depth;
40+
}
41+
if (cur.node.left != null) {
42+
q.add(new Data(cur.node.left, cur.depth + 1));
43+
}
44+
if (cur.node.right != null) {
45+
q.add(new Data(cur.node.right, cur.depth + 1));
46+
}
47+
}
48+
return depth;
49+
}
50+
}
51+

0 commit comments

Comments
 (0)