jayati

Construct Binary Tree from Inorder and Postorder Traversal

Mar 15th, 2023
246
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.20 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.     TreeNode* construct(vector<int>& in, int inStart, int inEnd, vector<int>& post, int postStart, int postEnd, unordered_map<int, int>& ump) {
  14.         if(inStart > inEnd || postStart > postEnd) return NULL;
  15.         TreeNode* root = new TreeNode(post[postEnd]);
  16.  
  17.         int in_ind = ump[root -> val];
  18.         int ele_left = in_ind - inStart;
  19.         root -> left = construct(in, inStart, in_ind - 1, post, postStart, postStart + ele_left - 1, ump);
  20.  
  21.         root -> right = construct(in, in_ind + 1, inEnd, post, postStart + ele_left, postEnd - 1, ump);
  22.  
  23.         return root;
  24.     }
  25. public:
  26.     TreeNode* buildTree(vector<int>& in, vector<int>& post) {
  27.         unordered_map<int, int> ump;
  28.         for(int i=0;i<in.size();i++) ump[in[i]] = i;
  29.         return construct(in, 0, in.size()-1, post, 0, post.size()-1, ump);
  30.     }
  31. };
Advertisement
Add Comment
Please, Sign In to add comment