-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path110.balanced-binary-tree.java
More file actions
37 lines (37 loc) · 1.07 KB
/
110.balanced-binary-tree.java
File metadata and controls
37 lines (37 loc) · 1.07 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
/**
* 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;
else {
return Math.abs(maxDepth(root.left)-maxDepth(root.right))<=1&&isBalanced(root.left)&&isBalanced(root.right);
}
}
public int maxDepth(TreeNode root) {
if (root!=null) {
Stack<TreeNode> level = new Stack<>();
level.add(root);
return lOrver(level)-1;
}else return 0;
}
public int lOrver(Stack<TreeNode> level){
if (level.size()==0) return 0;
else {
Stack<TreeNode> nextlevel = new Stack<>();
for (TreeNode root:level) {
if (root!=null){
nextlevel.add(root.left);
nextlevel.add(root.right);
}
}
return lOrver(nextlevel)+1;
}
}
}