Leetcode 110. Balanced Binary Tree

Leetcode 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 left and right subtrees of every node differ in height by no more than 1.

题目大意:
判断二叉树是否为高度平衡二叉树,其定义为每个结点的左右子树深度差小于1.

解题思路:
递归返回每个结点的左右子树深度,并判断深度差是否大于1.

代码1:

class Solution {
public:
    bool isBalanced(TreeNode* root) {
        if(!root)
            return true;
        return isBalanced(root->left) && isBalanced(root->right) && (abs(helper(root->left) - helper(root->right)) <= 1); 
    }
    
    int helper(TreeNode* root){
        if(!root)
            return 0;
        return max(helper(root->left), helper(root->right)) + 1;
    }
};

代码2 (优化):
如果子树不平衡则不计算深度直接返回-1

class Solution {
public:
    bool isBalanced(TreeNode* root) {
        if(helper(root) == -1)
            return false;
        return true;
    }
    
    int helper(TreeNode* root){
        if(!root)
            return 0;
        int left = helper(root->left);
        if(left == -1)
            return -1;
        int right = helper(root->right);
        if(right == -1)
            return -1;
        int diff = abs(left - right);
        if(diff > 1)
            return -1;
        return max(left, right) + 1;
    }
};

你可能感兴趣的:(Leetcode)