其他分享
首页 > 其他分享> > LKJZ55-2-平衡二叉树

LKJZ55-2-平衡二叉树

作者:互联网

LKJZ55-2-平衡二叉树 https://leetcode-cn.com/problems/ping-heng-er-cha-shu-lcof/ 平衡二叉树-二叉树中任意节点的左右子树的深度相差不超过1 需要复用求二叉树深度的代码 空树为平衡二叉树 平衡二叉树需要满足3个条件 1.左右子树高度差不超过1 2.左子树是平衡二叉树 3.右子树是平衡二叉树 递归终止条件为如果3个条件有一个不满足就return false
class Solution {
public:
    int maxdepth(TreeNode*root){
        //递归终止条件
        if(root==nullptr){
            return 0;
        }
        int leftdepth=maxdepth(root->left);
        int rightdepth=maxdepth(root->right);
        return max(leftdepth,rightdepth)+1;
    }
    bool isBalanced(TreeNode* root) {
        //一上来先考虑特殊情况-空树为平衡二叉树
        if(root==nullptr){
            return true;
        }
        //然后再分治递归
        int leftdepth=maxdepth(root->left);
        int rightdepth=maxdepth(root->right);
        //递归的终止条件为如果3个条件有一个条件不满足就return false跳出递归
        //1.左右子树高度差不差过1
        //2.左子树为平衡二叉树
        //3.右子树为平衡二叉树
        //之前求高度调用的是maxdepth,递归需要调用自身isBalanced
        return abs(leftdepth-rightdepth)<=1&&isBalanced(root->left)&&isBalanced(root->right);
    }
};

标签:return,int,二叉树,平衡,LKJZ55,root,maxdepth
来源: https://blog.csdn.net/A240428037/article/details/118854052