-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution.java
More file actions
48 lines (40 loc) · 1.24 KB
/
Solution.java
File metadata and controls
48 lines (40 loc) · 1.24 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
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
class TreeNodeInfo {
public int height;
public boolean isBalanced ;
public TreeNodeInfo(int height, boolean isBalanced) {
this.height = height;
this.isBalanced = isBalanced;
}
}
public boolean isBalanced(TreeNode root) {
TreeNodeInfo info = getTreeNodeInfo(root);
return info.isBalanced;
}
private TreeNodeInfo getTreeNodeInfo(TreeNode node) {
TreeNodeInfo info = new TreeNodeInfo(0, true);
if (node == null) {
return info;
}
TreeNodeInfo left = getTreeNodeInfo(node.left);
if (left.isBalanced) {
TreeNodeInfo right = getTreeNodeInfo(node.right);
if (right.isBalanced) {
info.isBalanced = Math.abs(left.height - right.height) < 2;
info.height = Math.max(left.height, right.height) + 1;
return info;
}
}
info.isBalanced = false;
return info;
}
}