1、首先想到的就是递归
2、根据每次递归的前序序列的首项,就是根节点,再通过这个根节点去找到中序序列该节点的位置
3、根据中序序列中根节点的位置,分为左右两部分,分别为左子树和右子树,然后再把截取后的前序和中序递归,直到序列长度为1就结束
代码解析:
function TreeNode(x) { this.val = x; this.left = null; this.right = null; } function reConstructBinaryTree(pre, vin) { if (pre.length == 0 || vin.length == 0) { return } // 取前序第0项为根节点 let head = pre[0] const tree = new TreeNode(head) // 在中序找到根节点的位置,以这项分为左右子树 const index = vin.indexOf(head) let leftVin = vin.slice(0, index), leftL = leftVin.length, leftPre = pre.slice(1, 1 + leftL); tree.left = reConstructBinaryTree(leftPre, leftVin) let rightVin = vin.slice(index + 1, vin.length), rightPre = pre.slice(1 + leftL); tree.right = reConstructBinaryTree(rightPre, rightVin); return tree }