题目描述
输入一棵二叉树,判断该二叉树是否是平衡二叉树。
参考思路
根据平衡二叉树(AVL)的特点,左右子树的深度差不超过1.因此可以获得左右子树的深度来判断当前结点是否满足平衡二叉树。为了避免重复,选择使用后序遍历,从叶子结点开始从下网上判断,是否满足平衡二叉树,不满足返回-1;满足则返回高度继续递归回溯。
参考代码
public class Solution {
public boolean IsBalanced_Solution(TreeNode root) {
return getDeep(root) != -1;
}
public int getDeep(TreeNode root){
if(root == null){
return 0;
}
//分别求左右子树的深度
int leftDeep = getDeep(root.left);
int rightDeep = getDeep(root.right);
//如果左右子树不满足AVL,或者该结点不满足AVL,则返回-1
if(leftDeep == -1 || rightDeep == -1 || Math.abs(leftDeep - rightDeep) > 1)
return -1;
//返回该结点的深度
else return (leftDeep > rightDeep ? leftDeep:rightDeep)+1;
}
}