Repository navigation
Expand file tree
/
Copy pathConvert BST to Array Sorted.cpp
More file actions
90 lines (73 loc) · 1.71 KB
/
Copy pathConvert BST to Array Sorted.cpp
File metadata and controls
90 lines (73 loc) · 1.71 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
86
87
88
89
90
#include<iostream>
using namespace std;
int arr[100];
struct node
{
int key;
struct node *left, *right;
};
struct node *newNode(int item)
{
struct node *temp = new node;
temp->key = item;
temp->left = temp->right = NULL;
return temp;
}
struct node* insert(struct node* node, int key)
{
if (node == NULL)
return newNode(key);
if (key < node->key)
node->left = insert(node->left, key);
else
node->right = insert(node->right, key);
return node;
}
//printing the whole tree
void PrintTree(struct node *root)
{
if (root == NULL)
return;
cout<<root->key<<" ";
PrintTree(root->left);
PrintTree(root->right);
}
// Converting a BST into an Array
void BSTtoArray(node *root, int A[])
{
static int pos = 0;
if(root == NULL) return;
BSTtoArray(root->left, A);
A[pos++] = root->key;
BSTtoArray(root->right, A);
}
int treeSize(node *root) {
if(root == NULL) return 0;
else
return treeSize(root->left) + treeSize(root->right) + 1;
}
// Drive Code
int main()
{
struct node *root = NULL;
root = insert(root, 50);
root = insert(root, 13);
root = insert(root, 20);
root = insert(root, 40);
root = insert(root, 3);
root = insert(root, 9);
root = insert(root, 80);
root = insert(root, 4);
root = insert(root, 60);
root = insert(root, 111);
cout<<"Printing Tree: ";
PrintTree(root);
int treeSZ = treeSize(root);
int *A = new int[treeSZ];
BSTtoArray(root, A);
cout << "\nNew Array: ";
for(int i = 0; i < treeSZ; i++)
cout << A[i] << " ";
cout << endl;
return 0;
}