题目描述
输入一棵二叉树,判断该二叉树是否是平衡二叉树。
import java.lang.Math;
public class Solution {
public boolean IsBalanced_Solution(TreeNode root) {
if(root==null){
return true;
}
if(Math.abs(TreeDepth(root.left)-TreeDepth(root.right))<=1){
if(root.left==null&&root.right==null){
return true;
}
else if(root.left!=null&&root.right==null){
return IsBalanced_Solution(root.left);
}
else if(root.left==null&&root.right!=null){
return IsBalanced_Solution(root.right);
}
else{
return IsBalanced_Solution(root.left)&&IsBalanced_Solution(root.right);
}
}
return false;
}
public int TreeDepth(TreeNode root){
if(root==null){
return 0;
}
if(root.left==null&&root.right==null){
return 1;
}
return 1+MaxTreeDepth(root.left,root.right);
}
public int MaxTreeDepth(TreeNode left,TreeNode right){
return TreeDepth(left)>TreeDepth(right)?TreeDepth(left):TreeDepth(right);
}
}