forked from kamyu104/LintCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
balanced-binary-tree.cpp
41 lines (37 loc) · 961 Bytes
/
balanced-binary-tree.cpp
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
29
30
31
32
33
34
35
36
37
38
39
40
41
// Time: O(n)
// Space: O(h)
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param root: The root of binary tree.
* @return: True if this Binary tree is Balanced, or false.
*/
bool isBalanced(TreeNode *root) {
return isBalancedRecu(root).first;
}
pair<bool, int> isBalancedRecu(TreeNode *root) {
if (root == nullptr) {
return {true, 0};
}
pair<bool, int> left = isBalancedRecu(root->left);
pair<bool, int> right = isBalancedRecu(root->right);
if (left.first && right.first && abs(left.second - right.second) <= 1) {
return {true, max(left.second, right.second) + 1};
}
else {
return {false, 0};
}
}
};