-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution.java
More file actions
83 lines (72 loc) · 1.77 KB
/
Solution.java
File metadata and controls
83 lines (72 loc) · 1.77 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
71
72
73
74
75
76
77
78
79
80
81
82
83
package Tree.easy.No_110_Balanced_Binary_Tree;
import Tree.TreeNode;
/**
* FileName: Solution
* Author: EdisonLi的家用MacBook Pro
* Date: 2019-03-27 11:26
* Description: 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.
*
* Example 1:
*
* Given the following tree [3,9,20,null,null,15,7]:
*
* 3
* / \
* 9 20
* / \
* 15 7
* Return true.
*
* Example 2:
*
* Given the following tree [1,2,2,3,3,null,null,4,4]:
*
* 1
* / \
* 2 2
* / \
* 3 3
* / \
* 4 4
* Return false.
*/
public class Solution {
private boolean res = true;
public boolean isBalanced(TreeNode root) {
if (root == null) return true;
handleBalanced(root);
return res;
}
private int handleBalanced(TreeNode node) {
if (node == null) return 0;
int l = handleBalanced(node.left);
int r = handleBalanced(node.right);
if (Math.abs(l - r) > 1)
res = false;
return 1 + Math.max(l, r);
}
public boolean isBalanced1(TreeNode root) {
if (root == null) return true;
else {
int l = dfs(root.left);
int r = dfs(root.right);
if (l - r > 1 || l - r < -1)
return false;
else
return isBalanced1(root.left) && isBalanced1(root.right);
}
}
private int dfs(TreeNode node) {
if (node == null) return 0;
else {
int l = dfs(node.left) + 1;
int r = dfs(node.right) + 1;
return l > r ? l : r;
}
}
}