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

相关题目

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