描述
输入一棵二叉树,判断该二叉树是否是平衡二叉树。
代码
根据平衡二叉树的定义,我们可以根据求二叉树深度的算法,后序遍历求出左右子树的深度差,并做出判断
public class Solution {
private boolean isBalanced=true;
public boolean IsBalanced_Solution(TreeNode root) {
core(root);
return isBalanced;
}
public int core(TreeNode root){
if(root==null){
return 0;
}
int left=core(root.left)+1;
int right=core(root.right)+1;
if(Math.abs(left-right)>1){
isBalanced=false;
return 0;
}
return left>right?left:right;
}
}