剑指Offer面试题6:重建二叉树(JS实现)
题目描述:输入某二叉树的前序遍历和中序遍历,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含有重复的数字。例如,前序遍历序列:{1,2,3,7,3,5,6,8},中序遍历序列:{4,7,2,1,5,3,8,6}
var Node = function (key) {
this .key = key;
this .left = null ;
this .right = null ;
}
function ConstructCore (preorder ,inorder) {
if (preorder == null || inorder == null ){
return null ;
}
var rootValue = parseInt (preorder[0 ]);
var root = new Node(rootValue);
if (rootValue == inorder) {
return root;
}
var leftLen = 0 ;
while (inorder[leftLen] != rootValue) {
leftLen++;
}
if (leftLen > 0 ) {
root.left = ConstructCore(preorder.substring(1 , leftLen+1 ),
inorder.substring(0 , leftLen));
}
if (leftLen < preorder.length-1 ) {
root.right = ConstructCore(preorder.substring(leftLen+1 , preorder.length),
inorder.substring(leftLen+1 , preorder.length));
}
return root;
}
console.log(ConstructCore('12473568' , '47215386' ));