forked from xiaoyaoworm/Leetcode-java
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path110_isBalanced.java
95 lines (84 loc) · 2.36 KB
/
110_isBalanced.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
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
84
85
86
87
88
89
90
91
92
93
94
95
//Best solution: Calculate weight then check the Math.abs(l-r), if -1 set as -1 forever.
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public boolean isBalanced(TreeNode root) {
if(root == null) return true;
if (getDepth(root)==-1) return false;
return true;
}
public int getDepth(TreeNode root){
if(root == null) return 0;
int l = getDepth(root.left);
int r = getDepth(root.right);
if(l == -1 || r == -1) return -1;
if(Math.abs(l-r)>1) return -1;
return Math.max(l,r)+1;
}
}
//Use BFS to check balanced:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public boolean isBalanced(TreeNode root) {
if(root == null) return true;
LinkedList<TreeNode> queue = new LinkedList<TreeNode>();
queue.add(root);
while(!queue.isEmpty()){
TreeNode temp = queue.remove();
if(temp.left!=null){
queue.add(temp.left);
}
if(temp.right!=null){
queue.add(temp.right);
}
if(Math.abs(getDepth(temp.left)-getDepth(temp.right))<=1){
continue;
} else{
return false;
}
}
return true;
}
public int getDepth(TreeNode root){
if(root == null) return 0;
return Math.max(getDepth(root.left),getDepth(root.right))+1;
}
}
//Use DFS to check balanced:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public boolean isBalanced(TreeNode root) {
if(root == null) return true;
int left = getDepth(root.left);
int right = getDepth(root.right);
if((Math.abs(left-right)) > 1) return false;
return isBalanced(root.left) && isBalanced(root.right);
}
public int getDepth(TreeNode root){
if(root == null) return 0;
return Math.max(getDepth(root.left),getDepth(root.right))+1;
}
}