Balanced Binary Tree

class Solution {
public:
    bool isBalanced(TreeNode *root) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        bool flag=true;
        height(root,flag);
        return flag;
    }
    int height(TreeNode *root,bool &flag){
        if(!root) return 0;
        int left=height(root->left,flag);
        int right=height(root->right,flag);
        if(left-right>1||left-right<-1)
            flag=false;    
        return left>right?left+1:right+1;
    }
};
错误原因:bool一开始没有写传引用,导致很多测试样例没过。

你可能感兴趣的:(Balanced Binary Tree)