-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathBalanced_Binary_Tree.cpp
59 lines (44 loc) · 1.13 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
#include <iostream>
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
using namespace std;
class Solution {
public:
bool is_balanced = true;
bool isBalanced(TreeNode *root) {
if(root == NULL)
return true;
if(go_deep(root, 1) == -1)
return false;
return true;
}
int go_deep(TreeNode* node, int currDeepth){
int left = currDeepth;
int right = currDeepth;
if(node->left==NULL && node->right==NULL)
return currDeepth;
if(node->left!=NULL)
left = go_deep(node->left, currDeepth+1);
if(node->right!=NULL)
right = go_deep(node->right, currDeepth+1);
if(left == -1 || right == -1)
return -1;
if(right-left>1 || left-right>1)
return -1;
return left>right?left:right;
}
};
int main(){
Solution s = Solution();
TreeNode* root = new TreeNode(1);
root->left = new TreeNode(2);
root->right = new TreeNode(3);
root->left->left = new TreeNode(4);
root->left->right = new TreeNode(5);
root->left->left->right = new TreeNode(6);
cout << s.isBalanced(root);
}