题目地址(106. 从中序与后序遍历序列构造二叉树)

https://leetcode-cn.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/

题目描述

  1. 根据一棵树的中序遍历与后序遍历构造二叉树。
  2. 注意:
  3. 你可以假设树中没有重复的元素。
  4. 例如,给出
  5. 中序遍历 inorder = [9,3,15,20,7]
  6. 后序遍历 postorder = [9,15,7,20,3]
  7. 返回如下的二叉树:
  8. 3
  9. / \
  10. 9 20
  11. / \
  12. 15 7

前置知识


公司

  • 暂无

思路

image.png

关键点


代码

  • 语言支持:Java

Java Code:

  1. /**
  2. * Definition for a binary tree node.
  3. * public class TreeNode {
  4. * int val;
  5. * TreeNode left;
  6. * TreeNode right;
  7. * TreeNode() {}
  8. * TreeNode(int val) { this.val = val; }
  9. * TreeNode(int val, TreeNode left, TreeNode right) {
  10. * this.val = val;
  11. * this.left = left;
  12. * this.right = right;
  13. * }
  14. * }
  15. */
  16. class Solution {
  17. public TreeNode buildTree(int[] inorder, int[] postorder) {
  18. return loop(inorder, 0, inorder.length - 1, postorder, 0, postorder.length - 1);
  19. }
  20. public TreeNode loop(int[] inorder, int inLeft, int inRight,
  21. int[] postorder, int postLeft, int postRight) {
  22. //如果中序序列为空的话 就返回null
  23. if (inRight < inLeft ) {
  24. return null;
  25. }
  26. //找出根节点 也就是后序序列里的最后一个数
  27. int rootVal = postorder[postRight];
  28. TreeNode root = new TreeNode(rootVal);
  29. //将根节点的位置 在中序序列里找出
  30. int index = 0;
  31. for (int i = inLeft; i <= inRight; i++) {
  32. if (inorder[i] == rootVal) {
  33. index = i;
  34. break;
  35. }
  36. }
  37. //对序列分别进行拆分
  38. //左子树
  39. int leftSize = index - inLeft;
  40. root.left = loop(inorder, inLeft, index -1,
  41. postorder, postLeft, postLeft + leftSize -1);
  42. //右子树
  43. root.right = loop(inorder, index + 1, inRight,
  44. postorder, postLeft + leftSize, postRight - 1);
  45. return root;
  46. }
  47. }

复杂度分析

令 n 为数组长度。

  • 时间复杂度:106. 从中序与后序遍历序列构造二叉树 - 图2#card=math&code=O%28n%29&id=zK8hd)
  • 空间复杂度:106. 从中序与后序遍历序列构造二叉树 - 图3#card=math&code=O%28n%29&id=DTsoH)