/
Balanced Binary Tree.cpp
57 lines (50 loc) · 1.06 KB
/
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#include <iostream>
#include <vector>
using namespace std;
/**
* 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 isBal;
bool isBalanced(TreeNode *root) {
int depth = 0;
isBal = true;
postOrder(root, 0);
return isBal;
}
int postOrder(TreeNode *p, int depth){
int maxD, minD;
depth ++;
if(!isBal) return depth;
if(p == NULL) return depth;
maxD = postOrder(p->left, depth);
minD = postOrder(p->right, depth);
if(minD>maxD){
int tmp = maxD;
maxD = minD;
minD = tmp;
}
if( maxD - minD > 1){
isBal = false;
}
return maxD;
}
};
int main()
{
Solution s;
TreeNode *a, *b;
TreeNode root(1);
a = new TreeNode(2);
a->right = new TreeNode(3);
root.left = a;
cout<< s.isBalanced(&root)<<endl;
return -1;
}