0%

面试题 04.04. 检查平衡性

面试题 04.04. 检查平衡性

bottom-up

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
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool isBalanced(TreeNode* root) {
check(root);
return ret;
}
private:
bool ret = true;
int check(TreeNode* root)
{
if(!root || !ret)
return 0;
auto left = check(root->left);
auto right = check(root->right);
if(abs(left -right) > 1)
ret = false;
return max(left, right) + 1;
}
};