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. public class Solution {
  4. public TreeNode buildTree(int[] preorder, int[] inorder) {
  5. return buildTree(preorder, 0, preorder.length,
  6. inorder, 0, inorder.length);
  7. }
  8. TreeNode buildTree(int[] preorder, int begin1, int end1,
  9. int[] inorder, int begin2, int end2) {
  10. if (begin1 == end1) return null;
  11. if (begin2 == end2) return null;
  12. TreeNode root = new TreeNode(preorder[begin1]);
  13. int inRootPos = find(inorder, begin2, end2, preorder[begin1]);
  14. int leftSize = inRootPos - begin2;
  15. root.left = buildTree(preorder, begin1 + 1, begin1 + leftSize + 1,
  16. inorder, begin2, begin2 + leftSize);
  17. root.right = buildTree(preorder, begin1 + leftSize + 1, end1,
  18. inorder, inRootPos + 1, end2);
  19. return root;
  20. }
  21. private static int find(int[] array, int begin, int end, int val) {
  22. for (int i = begin; i < end; ++i) {
  23. if (array[i] == val) return i;
  24. }
  25. return -1;
  26. }
  27. }

相关题目

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