【刷题之路】判断平衡二叉树

来源:互联网 发布:中国人工智能协会 编辑:程序博客网 时间:2024/05/19 15:26

采用递归的方式,不断返回左右子树中较大的值作为当前节点的depth,当前节点又与其他一个节点作为上一节点的左右子树,一旦某一左右子树递归叠加深度差大于一,以后全部返回false

class CheckBalance {

public:
    bool check(TreeNode* root) {
        // write code here
        int depth=0;
        return helper(root,depth);
    }
     bool helper(TreeNode* pRoot, int &Depth){
        if (pRoot == NULL){
            Depth = 0;  //递归结束条件,开始返回值
            return true;
        }
 
        int left, right;
        if (helper(pRoot->left, left) && helper(pRoot->right, right)){  //只有当之前返回值全为ture时,叠加才在继续
            Depth = max(left, right) + 1;  //当前节点之下的左右子树的较大深度为当前节点深度
            int dif = left - right;  //比较当前递归节点的左右子树差
            if (dif <= 1 && dif >= -1){
                return true;  //如果条件不成立,则返回之后的false,并且之后的if条件均不执行,一直返回false到结束
            }
        }
 
        return false;
    }
};
0 0