xxleyi / loop_invariants

记录以及整理「循环不变式」视角下的算法题解

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

leetcode 105. 从前序与中序遍历序列构造二叉树

xxleyi opened this issue · comments

题:

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

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

例如,给出

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

返回如下的二叉树:

    3
   / \
  9  20
    /  \
   15   7

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。


解:

此题对于夯实二叉树遍历规则很有帮助,尤其注意那个注意:可以假设树中没有重复元素

前序:VLR,中序:LVR,后序 LRV。其中 V 为当前根节点,LR 为左右子树。

使用 VLRLVR 重构无重复元素的二叉树是可行的。因为当前根节点的 V 始终是前序的第一个元素,同时又能通过中序得到左右子树。如此循环往复,终能重构出遍历之前的二叉树。

这里的「循环不变式」就是正确拆分每一个 VLRLVR

var buildTree = function(preorder, inorder) {
  if (preorder.length == 0) {
    return null
  }

  let v = preorder[0]
  let vIndex = inorder.indexOf(v)
  let lPreorder = preorder.slice(1, vIndex + 1)
  let rPreorder = preorder.slice(vIndex + 1)
  let lInorder = inorder.slice(0, vIndex)
  let rInorder = inorder.slice(vIndex + 1)

  let root = new TreeNode(v)
  root.left = buildTree(lPreorder, lInorder)
  root.right = buildTree(rPreorder, rInorder)
  return root
};