-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmax_depth_bt.java
More file actions
43 lines (41 loc) · 1.05 KB
/
max_depth_bt.java
File metadata and controls
43 lines (41 loc) · 1.05 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
public class Solution {
public int maxDepth(TreeNode root) {
// Start typing your Java solution below
// DO NOT write main() function
if(root==null) return 0;
Queue<TreeNode> q = new LinkedList<TreeNode>();
q.add(root);
int nodesNum = 1,level=0;
while(!q.isEmpty()) {
level++;
int j = nodesNum;
nodesNum = 0;
for(int i=0;i<j;i++) {
TreeNode n = q.remove();
if(n.left!=null) {
q.add(n.left);
nodesNum++;
}
if(n.right!=null) {
q.add(n.right);
nodesNum++;
}
}
}
return level;
}
}
public int maxDepth() {
return(maxDepth(root));
}
private int maxDepth(Node node) {
if (node==null) {
return(0);
}
else {
int lDepth = maxDepth(node.left);
int rDepth = maxDepth(node.right);
// use the larger + 1
return(Math.max(lDepth, rDepth) + 1);
}
}