【题目描述】:输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。
【主要思路】:前序遍历是按照根节点、左节点、右节点的顺序进行,中序遍历是按照左节点、根节点、右节点的顺序进行遍历。
前序遍历序列中的第一个元素对应整个树的根节点rootNode
,在中序遍历序列中找到rootNode所在位置rootIndex
,rootIndex之前的所有元素为整个左子树,rootIndex后面的所有元素是整个右子树
;
同样的,找到左子树的跟节点和左子树和右子树,右子树也是一样。
利用递归的思想可以很容易实现,代码如下:
function ListNode(x){
this.val=x;
this.left=null;
this.right=null;
}
function reConstructBinartTree(pre,vin){
function build(preStart,preEnd,vinStart,vinEnd){
let rootNode=new ListNode(pre[preStart]);//根节点
let rootIndex=vin.indexOf(pre[preStart]),//根节点下标
leftLen=rootIndex-vinStart;//左子树长度
if(leftLen>0){ //如果左子树长度大于0,则遍历左子树
rootNode.left=build(preStart+1,preStart+leftLen,vinStart,rootIndx-1)
}
if(leftLen<preEnd-preStart){ //存在右子树,则遍历右子树
rootNode.right=build(preStart+leftLen+1,preEnd,rootIndex+1,vinEnd)
}
return rootNode
}
let head=build(0,pre.length-1,0,vin.length-1)
return head
}