【LeetCode】110

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.

Solution:包含两重递归,一是算degth,一是判断平衡

判断主节点的左右节点深度大小差,如果不在(-1,1)内,返回false,否则,继续判断其左右节点是否属于平衡二叉树

class Solution {
public:
    int depth(TreeNode *node){
        if(!node)return 0;
        return max(depth(node->left), depth(node->right))+1;
    }
    bool isBalanced(TreeNode* root) {
        if(!root)return true;
        
        int ldepth=depth(root->left);
        int rdepth=depth(root->right);
        return abs(ldepth-rdepth)<=1 && isBalanced(root->left) && isBalanced(root->right);
    }
};
原文地址:https://www.cnblogs.com/irun/p/4739450.html