110. Balanced Binary Tree

Given a binary tree, determine if it is height-balanced.

For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.

O(n * h)

int getHeight(TreeNode* root){
    if(root == NULL) return 0;
    return max(getHeight(root->left), getHeight(root->right)) + 1;
}

bool isBalanced(TreeNode* root) {
    if(root == NULL) return true;
    
    int l = getHeight(root->left);
    int r = getHeight(root->right);
    if(abs(l - r) < 2) return isBalanced(root->left) && isBalanced(root->right);
    return false;
}

O(n)

修改一下求深度的递归函数

bool isBalanced(TreeNode* root) {
    return isBalancedHelper(root) != -1;
}

int isBalancedHelper(TreeNode* root){
    if(root == NULL) return 0;
    
    int l = isBalancedHelper(root->left);
    int r = isBalancedHelper(root->right);
    if(l < 0 || r < 0 || abs(r - l) > 1) return -1;
    
    return max(l, r) + 1;
}

你可能感兴趣的:(110. Balanced Binary Tree)