-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBalanceTree39.java
More file actions
67 lines (60 loc) · 1.69 KB
/
BalanceTree39.java
File metadata and controls
67 lines (60 loc) · 1.69 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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package offer;
/*
* 平衡二叉树
*/
public class BalanceTree39 {
/*
* 后序遍历
*/
public boolean IsBalanced_Solution(TreeNode23 root) {
int [] depth = {0};
return isBalanced_2(root, depth);
}
//效率高的方法
/**
*
* @param root
* @param depth
* 当前以root为根节点的树的高度
* @return
*/
boolean isBalanced_2(TreeNode23 root, int[] depth){
if (root == null) {
depth[0] = 0;
return true;
}
int[] left = {0};
int[] right = {0};
if (isBalanced_2(root.left, left) && isBalanced_2(root.right, right)) {
int diff = left[0] - right[0];
if (diff >= -1 && diff <= 1) {
depth[0] = 1 + (left[0] > right[0] ? left[0] : right[0]);
return true;
}else{
return false;
}
}
return false;
}
/*
*下面的方法是中序遍历的思想
*/
boolean isBalanced(TreeNode23 root){
if(root == null){
return true;
}
int left = new depthTree39_1().TreeDepth(root.left);
int right = new depthTree39_1().TreeDepth(root.right);
int diff = left - right;
if(diff > 1 || diff < -1){
return false;
}
return isBalanced(root.left) && isBalanced(root.right);
}
public static void main(String[] args) {
int[] a = { 8, 5, 12, 4, 7, -1, -1, -1, 3};
TreeNode23 root = null;
root = new TreeOperate23().createSquence(a, 0);
System.out.println(new BalanceTree39().IsBalanced_Solution(root));
}
}