-
Notifications
You must be signed in to change notification settings - Fork 0
/
Sword39.java
48 lines (42 loc) · 1.1 KB
/
Sword39.java
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
45
46
47
48
package offer.fourty;
import Myjar.TreeNode;
/**
* Created by colin on 2017/4/2.
*/
public class Sword39 {
public static void main(String[] args) {
TreeNode root = new TreeNode(0);
root.left = new TreeNode(1);
root.right = new TreeNode(2);
System.out.println(isBalanced(root));
}
public static boolean isBalanced(TreeNode root) {
maxDepth(root, 0);
// maxDepth(root);
return flag;
}
private static int maxDepth(TreeNode root) {
if (root == null) {
return -1;
}
int d1 = maxDepth(root.left);
int d2 = maxDepth(root.right);
if (Math.abs(d1 - d2) > 1) {
flag = false;
}
return 1 + Math.max(d1, d2);
}
public static boolean flag = true;
public static int maxDepth(TreeNode root,int d) {
if (root == null) {
return d;
}
d++;
int d2 = maxDepth(root.left, d);
int d3 = maxDepth(root.right, d);
if (Math.abs(d2 - d3) > 1) {
flag = false;
}
return Math.max(d2, d3);
}
}