110. 平衡二叉树

110. 平衡二叉树_第1张图片

自顶向下 

class Solution {
    public boolean isBalanced(TreeNode root) {
        if(root == null){
            return true;
        }else{
            return Math.abs(height(root.left) - height(root.right)) < 2 && isBalanced(root.left) && isBalanced(root.right);
        }
    }
    
    public int height(TreeNode node){
        if(node == null){
            return 0;
        }else {
            return Math.max(height(node.left),height(node.right)) + 1;
        }
    }
}

自底向上

class Solution {
    public boolean isBalanced(TreeNode root) {
        return height(root) >= 0;
    }

    public int height(TreeNode node){
        if(node == null){
            return 0;
        }
        int leftHeight = height(node.left);
        int rightHeight = height(node.right);
        if(leftHeight == -1 || rightHeight == -1 || Math.abs(leftHeight - rightHeight) > 1){
            return -1;
        }else {
            return Math.max(leftHeight,rightHeight) + 1;
        }
    }
}

你可能感兴趣的:(leetcode,leetcode,算法,职场和发展)