|
10 | 10 | * }; |
11 | 11 | */ |
12 | 12 | class Solution { |
13 | | -private: |
14 | | - unordered_map<int,int> mp; |
15 | | - TreeNode* help(vector<int>& in, vector<int>& pos, int left, int right, int rootidx){ |
16 | | - |
17 | | - if(left > right) |
18 | | - return NULL; |
19 | | - int val = pos[rootidx]; |
20 | | - TreeNode* node = new TreeNode(val); |
21 | | - int p = mp[val]; |
22 | | - node->right = help(in,pos,p+1,right,rootidx-1); |
23 | | - node->left = help(in,pos,left,p-1,rootidx-1-(right-p)); |
24 | | - |
25 | | - return node; |
26 | | - } |
27 | 13 | public: |
28 | | - TreeNode* buildTree(vector<int>& in, vector<int>& pos) { |
29 | | - for(int i=0;i<in.size();i++){ |
30 | | - mp[in[i]]=i; |
| 14 | + unordered_map<int, int> inorderMap; |
| 15 | + TreeNode *buildTreeHelper(vector<int> &postorder, int i, int j, int &postorderIndex) { |
| 16 | + if(i > j) return NULL; |
| 17 | + |
| 18 | + int postorderValue = postorder[postorderIndex]; //get the postorder value to create the new node |
| 19 | + TreeNode *root = new TreeNode(postorderValue); //create new node |
| 20 | + |
| 21 | + int inorderIndex = inorderMap[postorderValue]; //get the index for dividing the inorder array into two parts |
| 22 | + postorderIndex--; //decrement the preorderIndex for next recursive call |
| 23 | + |
| 24 | + //recurse for right subtree first and then the left subtree(since its a postorder traversal) |
| 25 | + root->right = buildTreeHelper(postorder, inorderIndex + 1, j, postorderIndex); |
| 26 | + root->left = buildTreeHelper(postorder, i, inorderIndex - 1, postorderIndex); |
| 27 | + |
| 28 | + |
| 29 | + return root; |
| 30 | + } |
| 31 | + |
| 32 | + TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) { |
| 33 | + |
| 34 | + if(postorder.size() == 0 or inorder.size() == 0) { |
| 35 | + return NULL; |
| 36 | + } |
| 37 | + |
| 38 | + int idx = 0; |
| 39 | + for(auto ele : inorder) { |
| 40 | + inorderMap[ele] = idx++; |
31 | 41 | } |
32 | | - |
33 | | - return help(in,pos,0,in.size()-1,pos.size()-1); |
| 42 | + |
| 43 | + int i = 0, j = postorder.size() - 1; |
| 44 | + int postorderIndex = postorder.size() - 1; |
| 45 | + |
| 46 | + return buildTreeHelper(postorder, i, j, postorderIndex); |
34 | 47 | } |
35 | 48 | }; |
36 | | - |
|
0 commit comments