21.判断一棵树是不是平衡二叉树

176 阅读1分钟

一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过1。

三点注意事项:

左子树是平衡二叉树

右子树是平衡二叉树

左右子树高度不超过1

public class Solution {
    public boolean IsBalanced_Solution(TreeNode root) {
            if(root == null){
                return true;
            }
        
        return Math.abs(depthTree(root.left)-depthTree(root.right))<=1 && IsBalanced_Solution(root.left) && IsBalanced_Solution(root.right);
        
    }
    //计算树的高度
    private int depthTree(TreeNode node){
        if(node == null){
            return 0;
        }
        int left = depthTree(node.left);
        int right = depthTree(node.right);
        return (left>right?left:right)+1;
        
    }
}