889. Construct Binary Tree from Preorder and Postorder Traversal
Given two integer arrays, preorder and postorder where preorder is the preorder traversal of a binary tree of distinct values and postorder is the postorder traversal of the same tree, reconstruct and return the binary tree.
If there exist multiple answers, you can return any of them.
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 class Solution { TreeNode* helper (vector<int >& preorder, vector<int >& postorder, int & pre, int & post, unordered_set<int >& build) { if (pre == preorder.size () or post == postorder.size ()) return NULL ; if (preorder[pre] == postorder[post]) { build.insert (preorder[pre]); post++; return new TreeNode (preorder[pre++]); } TreeNode* node = new TreeNode (preorder[pre]); build.insert (preorder[pre++]); node->left = helper (preorder,postorder,pre,post,build); if (pre == preorder.size () or post == postorder.size ()) return node; if (build.count (postorder[post])) { post++; return node; } node->right = helper (preorder,postorder,pre,post,build); post++; return node; } public : TreeNode* constructFromPrePost (vector<int >& preorder, vector<int >& postorder) { int pre = 0 , post = 0 ; unordered_set<int > build; return helper (preorder,postorder,pre,post,build); } };