-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathMain55II.java
42 lines (38 loc) · 971 Bytes
/
Main55II.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
package JZOffer2;
public class Main55II {
public boolean isBalanced(TreeNode root) {
if(root == null){
return true;
}
return Math.abs(dfs(root.left) - dfs(root.right)) <= 1 && isBalanced(root.left) && isBalanced(root.right);
}
private int dfs(TreeNode root) {
if(root == null){
return 0;
}
return Math.max(dfs(root.left) + 1, dfs(root.right) + 1);
}
}
class Main55II_1{
public boolean isBalanced(TreeNode root) {
return dfs(root) != -1;
}
private int dfs(TreeNode root) {
if(root == null){
return 0;
}
int left = dfs(root.left);
if(left == -1){
return -1;
}
int right = dfs(root.right);
if(right == -1){
return -1;
}
if(Math.abs(left - right) > 1){
return -1;
}else{
return Math.max(left, right) + 1;
}
}
}