Construct Binary Tree from Preorder and Inorder Traversal

描述

Given preorder and inorder 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 Preorder and Inorder Traversal
  2. // 递归,时间复杂度O(n),空间复杂度O(\logn)
  3. class Solution {
  4. public:
  5. TreeNode* buildTree(vector& preorder, vector& inorder) {
  6. return buildTree(begin(preorder), end(preorder),
  7. begin(inorder), end(inorder));
  8. }
  9. template
  10. TreeNode* buildTree(InputIterator pre_first, InputIterator pre_last,
  11. InputIterator in_first, InputIterator in_last) {
  12. if (pre_first == pre_last) return nullptr;
  13. if (in_first == in_last) return nullptr;
  14. auto root = new TreeNode(*pre_first);
  15. auto inRootPos = find(in_first, in_last, *pre_first);
  16. auto leftSize = distance(in_first, inRootPos);
  17. root->left = buildTree(next(pre_first), next(pre_first,
  18. leftSize + 1), in_first, next(in_first, leftSize));
  19. root->right = buildTree(next(pre_first, leftSize + 1), pre_last,
  20. next(inRootPos), in_last);
  21. return root;
  22. }
  23. };

相关题目

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