输入一棵二叉树,判断该二叉树是否是平衡二叉树。
在这里,我们只需要考虑其平衡性,不需要考虑其是不是排序二叉树
解析:平衡二叉树的概念:左右子树的高度(深度)相差不超过1;
之前已经计算过二叉树的深度,这里再次用到。
代码:
public class Solution {
public boolean IsBalanced_Solution(TreeNode root) {
if(root == null)
return true;
if(root.left == null && root.right == null)
return true;
int left = Deepth(root.left);
int right = Deepth(root.right);
return Math.abs(left-right) <= 1;
}
//计算二叉树的深度
public int Deepth(TreeNode root){
if(root == null)
return 0;
int left = Deepth(root.left);
int right = Deepth(root.right);
return Math.max(left,right) + 1;
}
}