-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathSolution110.java
More file actions
44 lines (36 loc) · 831 Bytes
/
Solution110.java
File metadata and controls
44 lines (36 loc) · 831 Bytes
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 algorithm.leetcode;
/**
* @author: mayuan
* @desc: 平衡二叉树
* @date: 2019/03/07
*/
public class Solution110 {
public boolean isBalanced(TreeNode root) {
return dfs(root) != -1;
}
public int dfs(TreeNode root) {
if (null == root) {
return 0;
}
int leftHeight = dfs(root.left);
if (leftHeight == -1) {
return -1;
}
int rightHeight = dfs(root.right);
if (rightHeight == -1) {
return -1;
}
if (Math.abs(leftHeight - rightHeight) > 1) {
return -1;
}
return Math.max(leftHeight, rightHeight) + 1;
}
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
}