forked from rohitbarha/hello-world
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBSTBalance.cpp
More file actions
85 lines (71 loc) · 1.42 KB
/
Copy pathBSTBalance.cpp
File metadata and controls
85 lines (71 loc) · 1.42 KB
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
#include <iostream>
#include <cmath>
using namespace std;
class TreeNode {
public:
int data;
TreeNode* left;
TreeNode* right;
TreeNode(int d) {
data = d;
left = NULL;
right = NULL;
}
};
TreeNode* insertInBST(TreeNode* root, int x) {
if (root == NULL) {
TreeNode* tmp = new TreeNode(x);
return tmp;
}
if (x < root->data) {
root->left = insertInBST(root->left , x);
return root;
} else {
root->right = insertInBST(root->right, x);
return root;
}
}
TreeNode* createBST() {
TreeNode* root = NULL;
int x;
cin >> x;
//Take input until user inputs -1
while (true) {
if (x == -1) break;
root = insertInBST(root, x);
cin >> x;
}
return root;
}
//Calculate height of tree with given root
int height(TreeNode* root) {
if (root == NULL) return 0;
int leftHt = height(root->left);
int rightHt = height(root->right);
int curHt = max(leftHt, rightHt) + 1;
return curHt;
}
//Check whether tree is balanced or not
bool isHeightBalanced(TreeNode* root) {
if (!root) {
return true;
}
int leftHt = height(root->left);
int rightHt = height(root->right);
if (abs(leftHt - rightHt) > 1)
return false;
return isHeightBalanced(root->left) && isHeightBalanced(root->right);
}
int main() {
//Input BST
cout<<"Input Tree elements : ";
TreeNode* root = createBST();
cout << "Given BST is Balanced : ";
if (isHeightBalanced(root)) {
cout << "True";
}
else {
cout << "False";
}
return 0;
}