public class Solution {
public boolean IsBalanced_Solution(TreeNode root) {
if(root == null) return true;
dfs(root);
//show(root);
if(root.left==null && root.right==null) return true;
if(root.left==null && root.right!=null) {
if(root.right.depth < 2) return true;
else return false;
}
if(root.left!=null && root.right==null) {
if(root.left.depth < 2) return true;
else return false;
}
if(abs(root.left.depth - root.right.depth) < 2) {
if(IsBalanced_Solution(root.left) && IsBalanced_Solution(root.right)) return true;
}
return false;
}
public int dfs(TreeNode root) {
if(root == null) return 0;
int num1 = dfs(root.left);
int num2 = dfs(root.right);
root.depth = (num1>num2?num1:num2) + 1;
return (num1>num2?num1:num2) + 1;
}
public int abs(int a) {
return a>=0?a:(-a);
}
}
class TreeNode {
int val = 0;
int depth = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
public boolean IsBalanced_Solution(TreeNode root) {
if(root == null) return true;
dfs(root);
//show(root);
if(root.left==null && root.right==null) return true;
if(root.left==null && root.right!=null) {
if(root.right.depth < 2) return true;
else return false;
}
if(root.left!=null && root.right==null) {
if(root.left.depth < 2) return true;
else return false;
}
if(abs(root.left.depth - root.right.depth) < 2) {
if(IsBalanced_Solution(root.left) && IsBalanced_Solution(root.right)) return true;
}
return false;
}
public int dfs(TreeNode root) {
if(root == null) return 0;
int num1 = dfs(root.left);
int num2 = dfs(root.right);
root.depth = (num1>num2?num1:num2) + 1;
return (num1>num2?num1:num2) + 1;
}
public int abs(int a) {
return a>=0?a:(-a);
}
}
class TreeNode {
int val = 0;
int depth = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}