-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBalanced_Binary_Tree.java
More file actions
70 lines (55 loc) · 1.61 KB
/
Balanced_Binary_Tree.java
File metadata and controls
70 lines (55 loc) · 1.61 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
68
69
70
110. Balanced Binary Tree
Given a binary tree, determine if it is height-balanced.
For this problem, a height-balanced binary tree is defined as a binary
tree in which the depth of the two subtrees of every node
never differ by more than 1.
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
// Exceed time limit
public class Solution {
public boolean isBalanced(TreeNode root) {
if(root==null)
return true;
int lh = height(root.left);
int rh = height(root.right);
if(Math.abs(lh-rh)>1)
return false;
return isBalanced(root.left) && isBalanced(root.right);
}
public int height(TreeNode node) {
if(node==null)
return 0;
return 1 + Math.max(height(node.left), height(node.right));
}
}
/////////////////////////////////////////////////////////////////////////////////
//优化后的方法为:对于每一个节点,我们递归获得左右子树的深度,如果子树是平衡的,则返回真实的深度,若不平衡,直接返回-1
public class Solution {
public boolean isBalanced(TreeNode root) {
if(balanced(root)>=0)
return true;
else
return false;
}
public int balanced(TreeNode node) {
if(node==null)
return 0;
int l = balanced(node.left);
if(l==-1)
return -1;
int r = balanced(node.right);
if(r==-1)
return -1;
if(Math.abs(l-r)>1)
return -1;
else
return 1 + Math.max(l, r);
}
}