|
| 1 | +class Solution { |
| 2 | + public: |
| 3 | + void createMapping(vector<int> &in, map<int, int> &nodeToIndex, int n){ |
| 4 | + for(int i = 0; i < n; i++){ |
| 5 | + nodeToIndex[in[i]] = i; |
| 6 | + } |
| 7 | + |
| 8 | + } |
| 9 | + |
| 10 | + Node* solve(vector<int>&in , vector<int> postorder, int &index, int inOrderStart, int inOrderEnd, int n, map<int, int> &nodeToIndex){ |
| 11 | + if(index < 0 || inOrderStart > inOrderEnd) return NULL; |
| 12 | + |
| 13 | + int element = postorder[index--]; |
| 14 | + Node* root = new Node(element); |
| 15 | + |
| 16 | + int position = nodeToIndex[element]; |
| 17 | + |
| 18 | + root->right = solve(in, postorder, index, position + 1, inOrderEnd, n, nodeToIndex); |
| 19 | + root->left = solve(in, postorder, index, inOrderStart, position - 1, n, nodeToIndex); |
| 20 | + |
| 21 | + return root; |
| 22 | + } |
| 23 | + // Function to return a tree created from postorder and inoreder traversals. |
| 24 | + Node* buildTree(vector<int> inorder, vector<int> &postorder) { |
| 25 | + int n = postorder.size(); |
| 26 | + |
| 27 | + int postOrderIndex = n-1; |
| 28 | + map<int, int> nodeToIndex; |
| 29 | + createMapping(inorder, nodeToIndex, n); |
| 30 | + |
| 31 | + return solve(inorder, postorder, postOrderIndex, 0, n-1, n, nodeToIndex); |
| 32 | + } |
| 33 | +}; |
0 commit comments