-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathconstruct tree from inorder and preorder
48 lines (42 loc) · 1.11 KB
/
construct tree from inorder and preorder
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
/*
Given 2 Arrays of Inorder and preorder traversal. Construct a tree and print the Postorder traversal.
Input:
First line consists of T test cases. First line of every test case consists of N , denoting the number of elements in array. Second and
Third line of every test case consists of Inorder and preOrder traversal of a tree.
Output:
Single line output, return the Node of the tree.
**Use already defined preIndex in template
Constraints:
1<=T<=100
1<=N<=100
Example:
Input:
1
7
3 1 4 0 5 2 6
0 1 3 4 2 5 6
Output:
3 4 1 5 6 2 0
*/
int search(int in[], int inStrt , int inEnd, int tNode){
int i;
for(i=inStrt; i<=inEnd; i++)
{
if(in[i] == tNode)
return i;
}
}
//from inorder and preorder
Node* buildTree(int in[],int pre[], int inStrt, int inEnd)
{
// preIndex=0;
if(inStrt > inEnd)
return NULL;
Node *tNode = newNode(pre[preIndex++]);
if(inStrt == inEnd)
return tNode;
int inIndex = search(in, inStrt, inEnd, tNode->data);
tNode->left = buildTree(in,pre,inStrt, inIndex-1);
tNode->right = buildTree(in,pre,inIndex+1, inEnd);
return tNode;
}