forked from algorithm009-class01/algorithm009-class01
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMaxDepth.java
More file actions
44 lines (38 loc) · 1.09 KB
/
MaxDepth.java
File metadata and controls
44 lines (38 loc) · 1.09 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
44
package recur;
public class MaxDepth {
public static void main(String[] args) {
TreeNode left = new TreeNode(1);
TreeNode right = new TreeNode(4,new TreeNode(3),new TreeNode(6));
TreeNode root = new TreeNode(5,left,right);
System.out.println(root.toString());
int r = maxDepth(root);
System.out.println(r);
}
private static int maxDepth(TreeNode root) {
if(null == root){
return 0;
}
return 1+Math.max(maxDepth(root.left),maxDepth(root.right));
}
public static class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
public TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
@Override
public String toString() {
return "TreeNode{" +
"val=" + val +
", left=" + left +
", right=" + right +
'}';
}
}
}