-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathis_balanced.cpp
More file actions
42 lines (33 loc) · 1006 Bytes
/
Copy pathis_balanced.cpp
File metadata and controls
42 lines (33 loc) · 1006 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
36
37
38
39
40
#include <cstdlib>
#include <algorithm>
class BinTree {
BinTree *left, *right;
struct Helper {
bool isBalanced;
int depth;
Helper(bool _is, int _depth) : isBalanced(_is), depth(_depth) {}
Helper() {}
};
Helper isBalancedH() {
Helper helperL = left ? left->isBalancedH() : Helper(true, 0),
helperR = right ? right->isBalancedH() : Helper(true, 0);
return Helper(helperL.isBalanced && helperR.isBalanced &&
std::abs(helperL.depth-helperR.depth) <= 1,
std::max(helperL.depth, helperR.depth) + 1);
}
public:
BinTree(BinTree *_left, BinTree *_right) : left(_left), right(_right) {}
~BinTree() {
if(left) delete left;
if(right) delete right;
}
bool isBalanced() { return isBalancedH().isBalanced; }
};
int main() {
// BinTree myTree(new BinTree(new BinTree(NULL, NULL), NULL), NULL); // FALSE
BinTree myTree(new BinTree(new BinTree(NULL, NULL), NULL), new BinTree(NULL, NULL)); // TRUE
if(myTree.isBalanced())
printf("TRUE\n");
else
printf("FALSE\n");
}