forked from VivekDubey9/Competitive-Programming-Algos
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Tree from Postorder and Inorder
122 lines (91 loc) · 2.61 KB
/
Tree from Postorder and Inorder
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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
Given inorder and postorder traversals of a Binary Tree in the arrays in[] and post[] respectively. The task is to construct the binary tree from these traversals.
Example 1:
Input:
N = 8
in[] = 4 8 2 5 1 6 3 7
post[] =8 4 5 2 6 7 3 1
Output: 1 2 4 8 5 3 6 7
Explanation: For the given postorder and
inorder traversal of tree the resultant
binary tree will be
1
/ \
2 3
/ \ / \
4 5 6 7
\
8
Example 2:
Input:
N = 5
in[] = 9 5 2 3 4
post[] = 5 9 3 4 2
Output: 2 9 5 4 3
Explanation:
the resultant binary tree will be
2
/ \
9 4
\ /
5 3
Your Task:
You do not need to read input or print anything. Complete the function buildTree() which takes the inorder, postorder traversals and the number of nodes in the tree as input parameters
and returns the root node of the newly constructed Binary Tree. The generated output contains the preorder traversal of the constructed tree.
Expected Time Complexity: O(N2)
Expected Auxiliary Space: O(N)
Constraints:
1 <= N <= 103
1 <= in[i], post[i] <= 10^3
Solution :
/* Tree node structure
struct Node
{
int data;
struct Node* left;
struct Node* right;
Node(int x){
data = x;
left = right = NULL;
}
};*/
//Function to return a tree created from postorder and inoreder traversals.
Node* newNode(int data);
Node* buildUtil(int in[], int post[], int inStrt,
int inEnd, int* pIndex, unordered_map<int, int>& mp)
{
// Base case
if (inStrt > inEnd)
return NULL;
/* Pick current node from Postorder traversal
using postIndex and decrement postIndex */
int curr = post[*pIndex];
Node* node = newNode(curr);
(*pIndex)--;
/* If this node has no children then return */
if (inStrt == inEnd)
return node;
/* Else find the index of this node in Inorder
traversal */
int iIndex = mp[curr];
/* Using index in Inorder traversal, construct
left and right subtress */
node->right = buildUtil(in, post, iIndex + 1,
inEnd, pIndex, mp);
node->left = buildUtil(in, post, inStrt,
iIndex - 1, pIndex, mp);
return node;
}
Node *buildTree(int in[], int post[], int len) {
unordered_map<int, int> mp;
for (int i = 0; i < len; i++)
mp[in[i]] = i;
int index = len - 1; // Index in postorder
return buildUtil(in, post, 0, len - 1, &index, mp);
}
Node* newNode(int data)
{
Node* node = (Node*)malloc(sizeof(Node));
node->data = data;
node->left = node->right = NULL;
return (node);
}