-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
NormalBSTtoBalancedBST.cpp
96 lines (87 loc) · 1.8 KB
/
NormalBSTtoBalancedBST.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
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
86
87
88
89
90
91
92
93
94
95
96
#include <bits/stdc++.h>
using namespace std;
struct Node
{
int data;
struct Node *left;
struct Node *right;
Node(int x){
data = x;
left = NULL;
right = NULL;
}
};
Node* insert(struct Node* node, int key){
if (node == NULL)
return new Node(key);
if (key < node->data)
node->left = insert(node->left, key);
else if (key > node->data)
node->right = insert(node->right, key);
return node;
}
void preOrder(Node* node)
{
if (node == NULL)return;
printf("%d ", node->data);
preOrder(node->left);
preOrder(node->right);
}
int height(struct Node* node)
{
if (node==NULL) return 0;
else
{
int lDepth = height(node->left);
int rDepth = height(node->right);
if (lDepth > rDepth)
return(lDepth+1);
else
return(rDepth+1);
}
}
Node* buildBalancedTree(Node* root);
int main()
{
int t;
cin>>t;
while(t--)
{
struct Node *root = NULL;
int n, temp;
cin>>n;
while(n--)
{
cin>>temp;
root = insert(root, temp);
}
// cout<<height(root)<<endl;
root = buildBalancedTree(root);
cout<<height(root)<<endl;
}
return 0;
}
// } Driver Code Ends
void store_nodes(Node* root,vector<Node*> &nodes){
if(root==NULL)
return;
store_nodes(root->left,nodes);
nodes.push_back(root);
store_nodes(root->right,nodes);
}
Node* construct_Tree(vector<Node*>&nodes,int start,int end){
if(start>end)
return NULL;
int mid=(start+end)/2;
Node* root=nodes[mid];
root->left=construct_Tree(nodes,start,mid-1);
root->right=construct_Tree(nodes,mid+1,end);
return root;
}
Node* buildBalancedTree(Node* root)
{
vector<Node*>nodes;
store_nodes(root,nodes);
int n=nodes.size();
return construct_Tree(nodes,0,n-1);
}