Construct Binary Tree from Inorder and Postorder Traversal

描述

Given inorder and postorder traversal of a tree, construct the binary tree.

Note:You may assume that duplicates do not exist in the tree.

分析

代码

  1. // Construct Binary Tree from Inorder and Postorder Traversal
  2. // 递归,时间复杂度O(n),空间复杂度O(\logn)
  3. class Solution {
  4. public:
  5. TreeNode* buildTree(vector& inorder, vector& postorder) {
  6. return buildTree(begin(inorder), end(inorder),
  7. begin(postorder), end(postorder));
  8. }
  9. template
  10. TreeNode* buildTree(BidiIt in_first, BidiIt in_last,
  11. BidiIt post_first, BidiIt post_last) {
  12. if (in_first ==in_last) return nullptr;
  13. if (post_first == post_last) return nullptr;
  14. const auto val = *prev(post_last);
  15. TreeNode* root = new TreeNode(val);
  16. auto in_root_pos = find(in_first, in_last, val);
  17. auto left_size = distance(in_first, in_root_pos);
  18. auto post_left_last = next(post_first, left_size);
  19. root->left = buildTree(in_first, in_root_pos, post_first, post_left_last);
  20. root->right = buildTree(next(in_root_pos), in_last, post_left_last,
  21. prev(post_last));
  22. return root;
  23. }
  24. };

相关题目

原文: https://soulmachine.gitbooks.io/algorithm-essentials/content/cpp/binary-tree/construction/construct-binary-tree-from-inorder-and-postorder-traversal.html