-
Notifications
You must be signed in to change notification settings - Fork 0
/
BalancedBinaryTree.cpp
52 lines (42 loc) · 1.16 KB
/
BalancedBinaryTree.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
#include<iostream>
#include<vector>
using namespace std;
struct TreeNode{
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
bool isBalanced(TreeNode* root) {
if(root==NULL) return true;
int ldepth=getDepth(root->left), rdepth=getDepth(root->right);
if(!(ldepth-rdepth>1 || rdepth-ldepth>1) && isBalanced(root->left) && isBalanced(root->right)){
return true;
}else{
return false;
}
}
int getDepth(TreeNode *root){
if(root==NULL) return 0;
int ldepth=getDepth(root->left), rdepth=getDepth(root->right);
return ldepth>rdepth?ldepth+1:rdepth+1;
}
};
int main(){
TreeNode *root=new TreeNode(1);
TreeNode *a=new TreeNode(2);
TreeNode *b=new TreeNode(3);
TreeNode *c=new TreeNode(4);
TreeNode *d=new TreeNode(5);
TreeNode *e=new TreeNode(6);
root->left=a;
root->right=b;
a->left=c;
a->right=d;
c->left=e;
Solution *solution=new Solution();
solution->isBalanced(root)?cout<<"True" : cout<<"False";
return 0;
}