forked from sachuverma/DataStructures-Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathConstruct Binary Tree from Inorder and Postorder Traversal.cpp
63 lines (55 loc) · 1.83 KB
/
Construct Binary Tree from Inorder and Postorder Traversal.cpp
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
/*
Construct Binary Tree from Inorder and Postorder Traversal
==========================================================
Given two integer arrays inorder and postorder where inorder is the inorder traversal of a binary tree and postorder is the postorder traversal of the same tree, construct and return the binary tree.
Example 1:
Input: inorder = [9,3,15,20,7], postorder = [9,15,7,20,3]
Output: [3,9,20,null,null,15,7]
Example 2:
Input: inorder = [-1], postorder = [-1]
Output: [-1]
Constraints:
1 <= inorder.length <= 3000
postorder.length == inorder.length
-3000 <= inorder[i], postorder[i] <= 3000
inorder and postorder consist of unique values.
Each value of postorder also appears in inorder.
inorder is guaranteed to be the inorder traversal of the tree.
postorder is guaranteed to be the postorder traversal of the tree.
*/
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution
{
public:
int postI;
TreeNode *build(vector<int> &post, unordered_map<int, int> &find, int s, int e)
{
if (s > e)
return NULL;
TreeNode *root = new TreeNode(post[postI--]);
if (s == e)
return root;
int idx = find[root->val];
root->right = build(post, find, idx + 1, e);
root->left = build(post, find, s, idx - 1);
return root;
}
TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder)
{
postI = postorder.size() - 1;
unordered_map<int, int> find;
for (int i = 0; i < inorder.size(); ++i)
find[inorder[i]] = i;
return build(postorder, find, 0, inorder.size() - 1);
}
};