来源

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/

描述

根据一棵树的前序遍历与中序遍历构造二叉树。

注意:
你可以假设树中没有重复的元素。

例如,给出
前序遍历 preorder = [3,9,20,15,7]
中序遍历 inorder = [9,3,15,20,7]

返回如下的二叉树:
3
/ \
9 20
/ \
15 7

题解

先序遍历的顺序是 Root -> Left -> Right,这就能方便的从根开始构造一棵树。
首先,preorder中的第一个元素一定是树的根,这个根又将inorder序列分成了左右两棵子树。现在我们只需要将先序遍历的数组中删除根元素,然后重复上面的过程处理左右两棵子树。

  1. class Solution {
  2. int preIdx = 0;
  3. int[] preorder;
  4. int[] inorder;
  5. Map<Integer, Integer> idxMap = new HashMap<>();
  6. public TreeNode helper(int inLeft, int inRight) {
  7. // if there is no element to construct subtrees
  8. if (inLeft == inRight) {
  9. return null;
  10. }
  11. // pick up preIdx element as a root
  12. int rootVal = preorder[preIdx];
  13. TreeNode root = new TreeNode(rootVal);
  14. // root splits inorder list into left and right subtrees
  15. int index = idxMap.get(rootVal);
  16. //recursion
  17. preIdx++;
  18. // build left subtree
  19. root.left = helper(inLeft, index);
  20. // build right subtree
  21. root.right = helper(index + 1, inRight);
  22. return root;
  23. }
  24. public TreeNode buildTree(int[] preorder, int[] inorder) {
  25. this.preorder = preorder;
  26. this.inorder = inorder;
  27. // build a hashMap value -> its index
  28. int idx = 0;
  29. for (Integer val : inorder) {
  30. idxMap.put(val, idx++);
  31. }
  32. return helper(0, inorder.length);
  33. }
  34. }

复杂度分析

  • 时间复杂度:105. 从前序与中序遍历序列构造二叉树(Construct Binary Tree from Preorder and Inorder Traversal) - 图1
  • 空间复杂度:105. 从前序与中序遍历序列构造二叉树(Construct Binary Tree from Preorder and Inorder Traversal) - 图2,存储整棵树的开销。