-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path57_binaryTree_balancedTreeCheck.cpp
More file actions
63 lines (58 loc) · 1.3 KB
/
57_binaryTree_balancedTreeCheck.cpp
File metadata and controls
63 lines (58 loc) · 1.3 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
#include <bits/stdc++.h>
using namespace std;
class node{
public:
int data;
node *left;
node *right;
node(int d){
this->data = d;
this->left = NULL;
this->right = NULL;
}
};
node* buildingTree(node* root){
cout << "Enter the data: " << endl;
int data;
cin >> data;
root = new node(data);
if(data == -1){
return NULL;
}
cout << "Inserting data at left: " << data << endl;
root->left = buildingTree(root->left);
cout << "Inserting data at right: " << data << endl;
root->right = buildingTree(root->right);
return root;
}
int maxDepth(node* root){
if(root == NULL)
return 0;
int left = maxDepth(root->left);
int right = maxDepth(root->right);
return max(left, right) + 1;
}
bool checkBalance(node* root){
if(root == NULL)
return true;
bool left = checkBalance(root->left);
bool right = checkBalance(root->right);
int diff = abs(maxDepth(root->left) - maxDepth(root->right)) <= 1;
if(left && right && diff){
return 1;
}
else{
return 0;
}
}
int main()
{
node *root = NULL;
root = buildingTree(root);
if(checkBalance(root)){
cout << "Tree is balanced tree.";
}
else{
cout << "Not a balanced tree";
}
}