-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnormalbsttobalancedbst.cpp
More file actions
80 lines (66 loc) · 1.35 KB
/
normalbsttobalancedbst.cpp
File metadata and controls
80 lines (66 loc) · 1.35 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
#include<bits/stdc++.h>
using namespace std;
struct Node
{
int data;
Node*left,*right;
};
void storeBSTNodes(Node*root,vector<Node*>&nodes)
{
if(root==NULL)
{
return;
}
storeBSTNodes(root->left,nodes);
nodes.push_back(root);
storeBSTNodes(root->right,nodes);
}
Node*buildTreeUtil(vector<Node*>&nodes,int start,int end)
{
if(start>end)
{
return NULL;
}
int mid = (start+end)/2;
Node*root = nodes[mid];
root->left = buildTreeUtil(nodes,start,mid-1);
root->right = buildTreeUtil(nodes,mid+1,end);
return root;
}
Node*buildTree(Node*root)
{
vector<Node*>nodes;
storeBSTNodes(root,nodes);
int n = nodes.size();
return buildTreeUtil(nodes,0,n-1);
}
Node*newNode(int data)
{
Node*node = new Node;
node->data = data;
node->left = node->right = NULL;
return (node);
}
void preOrder(Node*node)
{
if(node==NULL)
{
return;
}
cout<<node->data<<" ";
preOrder(node->left);
preOrder(node->right);
}
int main()
{
Node* root = newNode(10);
root->left = newNode(8);
root->left->left = newNode(7);
root->left->left->left = newNode(6);
root->left->left->left->left = newNode(5);
root = buildTree(root);
printf("Preorder traversal of balanced "
"BST is : \n");
preOrder(root);
return 0;
}