关于java:判断一个二叉树是否为平衡二叉树

1次阅读

共计 404 个字符,预计需要花费 2 分钟才能阅读完成。

均衡二叉树:它又称为 AVL 树,具备以下性质,它是一棵空树或者它的左右子树的高度差的绝对值不超过 1,并且左右两个子树都是一棵均衡二叉树。

public class Solution {public boolean isBalanced(TreeNode root) {if( root == null) {return true;}
        return Math.abs(getDepth(root.left) - getDepth(root.right)) <= 1 && isBalanced(root.left) && isBalanced(root.right));
    }
    
    public int getDepth(TreeNode root) {if( root == null) return 0;
        int left = getDepth(root.left);
        int right = getDepth(root.right);
        return Math.max(left, right) + 1;
    }
}
正文完
 0