输入一棵二叉树,判断该二叉树是否是平衡二叉树
IDEA
平衡二叉树(Balanced Binary Tree)具有以下性质:它是一 棵空树或它的左右两个子树的高度差的绝对值不超过1,并且左右两个子树都是一棵平衡二叉树。
按照平衡二叉树的性质来判断输入的二叉树是否为平衡二叉树,需要求二叉树深度的算法。
CODE
public class Solution {
public boolean IsBalanced_Solution(TreeNode root) {
if(root==null)
return true;
if(Math.abs(getDepth(root.left)-getDepth(root.right))>1)
return false;
return IsBalanced_Solution(root.left)&&IsBalanced_Solution(root.right);
}
public int getDepth(TreeNode root){
if(root==null)
return 0;
int left_depth=getDepth(root.left);
int right_depth=getDepth(root.right);
return left_depth>right_depth?left_depth+1:right_depth+1;
}
}