leetcode 110:平衡二叉树

直接选择用递归就可以了,因为需要求高度,所以需要求深度。

int maxDepth(TreeNode*root){
    if(root==NULL)return 0;
    TreeNode*l=root->left;
    TreeNode*r=root->right;
    return 1+std::max(maxDepth(l),maxDepth(r));
}

bool isBalanced(TreeNode*root){
    if(root==NULL)return true;
    TreeNode*l=root->left;
    TreeNode*r=root->right;
    if(std::abs(maxDepth(l)-maxDepth(r))>1)
        return false;
    else
        return isBalanced(l)&&isBalanced(r);
}

猜你喜欢

转载自blog.csdn.net/u013263891/article/details/82975044