Given inorder and postorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
For example, given
inorder = [9,3,15,20,7] postorder = [9,15,7,20,3]
Return the following binary tree:
3 / \ 9 20 / \ 15 7
Solution: Recursion
Similar to LC 105
Time complexity: O(n)
Space complexity: O(n)
C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
// Author: Huahua class Solution { public: TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) { unordered_map<int, int> pos; for (int i = 0; i < inorder.size(); i++) pos[inorder[i]] = i; function<TreeNode*(int, int, int, int)> buildTree = [&](int is, int ie, int ps, int pe) { if (ps > pe) return (TreeNode*)nullptr; int im = pos[postorder[pe]]; int pm = ps + (im - is) - 1; auto root = new TreeNode(postorder[pe]); root->left = buildTree(is, im - 1, ps, pm); root->right = buildTree(im + 1, ie, pm + 1, pe - 1); return root; }; return buildTree(0, inorder.size() - 1, 0, postorder.size() - 1); } }; |
Related Problems
- https://zxi.mytechroad.com/blog/tree/leetcode-105-construct-binary-tree-from-preorder-and-inorder-traversal/
- https://zxi.mytechroad.com/blog/tree/leetcode-1008-construct-binary-search-tree-from-preorder-traversal/
- https://zxi.mytechroad.com/blog/tree/leetcode-889-construct-binary-tree-from-preorder-and-postorder-traversal/
请尊重作者的劳动成果,转载请注明出处!花花保留对文章/视频的所有权利。
如果您喜欢这篇文章/视频,欢迎您捐赠花花。
If you like my articles / videos, donations are welcome.
Be First to Comment