-
Notifications
You must be signed in to change notification settings - Fork 94
Expand file tree
/
Copy pathbalanced-binary-tree.cpp
More file actions
35 lines (32 loc) · 905 Bytes
/
balanced-binary-tree.cpp
File metadata and controls
35 lines (32 loc) · 905 Bytes
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
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool isBalanced(TreeNode *root) {
// Note: The Solution object is instantiated only once and is reused by each test case.
bool f = true;
checkBalance(root, 0, f);
return f;
}
private:
int checkBalance(TreeNode *root, int level, bool &f) {
if(root == NULL)
return level - 1;
int lheight = checkBalance(root->left, level + 1, f);
if(f == false)
return level;
int rheight = checkBalance(root->right, level + 1, f);
if(f == false)
return level;
if(abs(lheight - rheight) > 1)
f = false;
return max(lheight, rheight);
}
};