Advertisement
nikunjsoni

106

Apr 30th, 2021
108
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.10 KB | None | 0 0
  1. /**
  2.  * Definition for a binary tree node.
  3.  * struct TreeNode {
  4.  *     int val;
  5.  *     TreeNode *left;
  6.  *     TreeNode *right;
  7.  *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
  8.  *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
  9.  *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
  10.  * };
  11.  */
  12. class Solution {
  13. unordered_map<int, int> inorderIndex;
  14. int curr = 0;
  15. public:
  16.     TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
  17.         for(int i=0; i<inorder.size(); i++)
  18.             inorderIndex[inorder[i]] = i;
  19.         curr = inorder.size()-1;
  20.         return constructTree(postorder, 0, inorder.size()-1);
  21.     }
  22.    
  23.     TreeNode* constructTree(vector<int> &postorder, int left, int right){
  24.         if(left > right) return NULL;
  25.        
  26.         int val = postorder[curr--];
  27.         TreeNode *root = new TreeNode(val);
  28.        
  29.         root->right = constructTree(postorder, inorderIndex[val]+1, right);
  30.         root->left = constructTree(postorder, left, inorderIndex[val]-1);
  31.         return root;
  32.     }
  33.    
  34. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement