剑指offer39 平衡二叉树

一个错误代码

class Solution {
public:
    bool IsBalanced_Solution(TreeNode* pRoot) {
        return IsBalancedCore(pRoot,0);
    }
    bool IsBalancedCore(TreeNode* pRoot,int &depth){
        if(pRoot == NULL){
            depth = 0;
            return true;
        }
        int left = 0;
        int right = 0;
        if(IsBalancedCore(pRoot->left,left) && IsBalancedCore(pRoot->right,right)){
            int diff = left - right;
            if(diff <= 1 && diff >= -1){
                depth = (left > right ? left:right) + 1;
                return true;
            }
        }
        return false;
    }
};

若改成int depth = 0;

   return IsBalancedCore(pRoot,depth);

就对了。IsBalancedCore这个函数的第二个参数是传参数,需要引用,用的时候不能为常量0,必须是一个参数。

IsBalancedCore中depth参数必须&引用,如果不引用,

depth = (left > right ? left:right) + 1;就无法修改depth,depth就一直是同一个值,无法记录depth的变化

class Solution {
public:
    bool IsBalanced_Solution(TreeNode* pRoot) {
        if(pRoot == NULL)
            return true;
        int depth;
        return IsBalanced_Core(pRoot,depth);
    }
    bool IsBalanced_Core(TreeNode* pRoot,int &depth){
        if(pRoot == NULL){
            depth = 0;
            return true;
        }
        int left,right;
        if(IsBalanced_Core(pRoot->left,left) && IsBalanced_Core(pRoot->right,right)){
            int diff = left - right;
            if(diff <= 1 && diff >= -1){
                depth = left > right ? left+1 : right+1;
                return true;
            }
        }
        return false;
    }
};
 
原文地址:https://www.cnblogs.com/ymjyqsx/p/7194680.html