-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbdtfrompreorder.cpp
More file actions
65 lines (54 loc) · 1.41 KB
/
bdtfrompreorder.cpp
File metadata and controls
65 lines (54 loc) · 1.41 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
//22.Construct Binary Search Tree where preorder traversal is given
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node *left;
struct node *right;
};
struct node* newNode (int data)
{
struct node* temp = (struct node *) malloc( sizeof(struct node) );
temp->data = data;
temp->left = temp->right = NULL;
return temp;
}
struct node* constructTreeUtil (int pre[], int* preIndex,int low, int high, int size)
{
if (*preIndex >= size || low > high)
return NULL;
struct node* root = newNode ( pre[*preIndex] );
*preIndex = *preIndex + 1;
if (low == high)
return root;
int i;
for ( i = low; i <= high; ++i )
if ( pre[ i ] > root->data )
break;
root->left = constructTreeUtil ( pre, preIndex, *preIndex, i - 1, size );
root->right = constructTreeUtil ( pre, preIndex, i, high, size );
return root;
}
struct node *constructTree (int pre[], int size)
{
int preIndex = 0;
return constructTreeUtil (pre, &preIndex, 0, size - 1, size);
}
void printInorder (struct node* node)
{
if (node == NULL)
return;
printInorder(node->left);
printf("%d ", node->data);
printInorder(node->right);
}
int main ()
{
int pre[] = {10, 5, 1, 7, 40, 50};
int size = sizeof( pre ) / sizeof( pre[0] );
struct node *root = constructTree(pre, size);
printf("Inorder traversal of the constructed tree: \n");
printInorder(root);
return 0;
}