[leetcode_110]Balanced Binary Tree

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

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
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;
    }
};
Licensed under CC BY-NC-SA 4.0