题目描述:输入二叉树的前序遍历和中序遍历的结果,重建出该二叉树。假设输入的前序遍历和和中序遍历的结果中都不含重复数字。例如输入的前序遍历序列{1,2, 4, 7, 3, 5, 6, 8}和中序遍历序列{4, 7, 2, 1, 5, 3, 8, 6},则重建二叉树并返回
function TreeNode(x) {
this.val = x
this.left = null
this.right = null
}
function reConstructBinaryTree(pre, vin) {
var len = pre.length
return createTree(pre, vin, 0, len-1, 0)
}
function createTree(pre, vin, first, end, rootIndex) {
var rootVal = pre[rootIndex],
midIndex = vin.indexOf(rootVal),
root = new TreeNode(rootVal)
if(midIndex > first) root.left = createTree(pre, vin, first, midIndex-1, rootIndex+1)
if(midIndex < end) root.right = createTree(pre, vin, midIndex+1, end, rootIndex+midIndex-first+1)
return root
}