题目描述
输入一棵二叉树,判断该二叉树是否是平衡二叉树。
平衡二叉树:任意左右结点深度不超过1
public class Solution {
public boolean IsBalanced_Solution(TreeNode root) {
if(root==null)
return true;
int left=TreeDepth(root.left);
int right=TreeDepth(root.right);
int dif=left-right;
if(dif>1 || dif<-1)
return false;
//递归判断是否是平衡二叉树
return IsBalanced_Solution(root.left) && IsBalanced_Solution(root.right);
}
//获取二叉树深度
private int TreeDepth(TreeNode root){
if(root==null)
return 0;
int leftDep=TreeDepth(root.left);
int rightDep=TreeDepth(root.right);
return (leftDep>rightDep)?leftDep+1:rightDep+1;
}
}