首页 » 编程之美 » 正文

[leetcode_110]Balanced Binary Tree

判断一棵树是否是平衡的二叉查找树。
一次AC附上代码:[原以为自己会超时的]

class Solution {
public:
    bool ans;
    bool isBalanced(TreeNode *root) {
        // IMPORTANT: Please reset any member data you declared, as
        // the same Solution instance will be reused for each test case.
        ans = true;
        if(root == NULL)
            return ans;
        Calc(root); 
        return ans;
    }
    int Calc(TreeNode *node)
    {
        if(node == NULL)
            return 0;
        int left = Calc(node->left) + 1;
        int right = Calc(node->right) + 1;
        if(abs(left - right) > 1)
        {
            ans = false;
        }
        if(left > right)
            return left;
        else
            return right;
    }
};

发表评论