OJ练习25——T110 Balanced Binary Tree

判断一棵树是否是平衡树。

平衡数的意思是,树左右子树高度之差不能超过1.

【思路】

递归判断每个子树是否是平衡数,需要调用高度计算的函数。

【my code】

bool isBalanced(TreeNode *root) {
        if(root==NULL)
            return true;
        if(isBalanced(root->left)&&isBalanced(root->right)){
            int hightl=depthoftree(root->left);
            int hightr=depthoftree(root->right);
            if(abs(hightl-hightr)<=1)
                return true;
            else
                return false;//注意else
        }
    }
    int depthoftree(TreeNode *root){
        if(root==NULL)
            return 0;
        int max1=depthoftree(root->left);
        int max2=depthoftree(root->right);
        return max(max1, max2)+1;
    }

【总结】

一次错:开始没有写false的情况,这样就不会返回false,不会有不平衡了。切记。

原文地址:https://www.cnblogs.com/ketchups-notes/p/4450946.html