1. 题目

给定两个整数数组inorderpostorder ,其中inorder是二叉树的中序遍历,postorder是同一棵树的后序遍历,请构造并返回这颗二叉树

示例1:
image.png

  1. 输入:inorder = [9, 3, 15, 20, 7], postorder = [9, 15, 7, 20, 3]
  2. 输出:[3, 9, 20, null, null, 15, 7]
  1. //中序和后序遍历验证二叉树
  2. var indexMap2 = [Int:Int]()
  3. func buildTreePostAndIn(_ postorder: [Int], _ inorder: [Int]) -> TreNode? {
  4. // 构造哈希映射,帮助我们后续可以快速定位根节点
  5. for i in 0..<postorder.count {
  6. indexMap[inorder[i]] = i
  7. }
  8. return submethod(postorder,inorder,0,postorder.count-1,0,inorder.count-1)
  9. }
  10. func submethod(_ postorder: [Int], _ inorder: [Int], _ postorder_left:Int, _ postorder_right: Int,_ inorder_left:Int, _ inorder_right:Int) -> TreNode? {
  11. if postorder_left > postorder_right {
  12. return nil
  13. }
  14. // 后序遍历中的最后一个节点就是根节点
  15. let postorder_root = postorder_right
  16. // 在中序遍历中定位根节点
  17. let inorder_root = indexMap[postorder[postorder_root]]!
  18. // 先把根节点建立出来
  19. let root2 = TreNode.init(t: postorder[postorder_root])
  20. // 得到左子树中的节点数目
  21. let size_left_subtree = inorder_root - inorder_left
  22. // 递归地构造左子树,并连接到根节点
  23. // 后序遍历中「从 左边界 开始的 size_left_subtree」个元素就对应了中序遍历中「从 左边界 开始到 根节点定位-1」的元素
  24. root2.left = submethod(postorder, inorder, postorder_left, postorder_left + size_left_subtree-1, inorder_left, inorder_root - 1)
  25. // 递归地构造右子树,并连接到根节点
  26. // 后序遍历中「从 左边界+左子树节点数目 开始到 右边界-1」的元素就对应了中序遍历中「从 根节点定位+1 到 右边界」的元素
  27. root2.right = submethod(postorder, inorder, postorder_left + size_left_subtree, postorder_right-1, inorder_root + 1, inorder_right)
  28. return root2;
  29. }