題目描述
輸入某二叉樹的前序遍歷和中序遍歷的結(jié)果,請重建出該二叉樹。假設(shè)輸入的前序遍歷和中序遍歷的結(jié)果中都不含重復(fù)的數(shù)字顶籽。例如輸入前序遍歷序列{1,2,4,7,3,5,6,8}和中序遍歷序列{4,7,2,1,5,3,8,6}厨钻,則重建二叉樹并返回。
思路:遞歸的方式不斷的對根節(jié)點(diǎn)的左子樹和右子樹進(jìn)行重建南捂。
/* function TreeNode(x) {
this.val = x;
this.left = null;
this.right = null;
} */
function reConstructBinaryTree(pre, vin)
{
if(pre.length==0&&vin.length==0)return null;
var boot=new TreeNode(pre[0]);
var index=vin.indexOf(pre[0]);
boot.left=reConstructBinaryTree(pre.slice(1,index+1),vin.slice(0,index));
boot.right=reConstructBinaryTree(pre.slice(index+1),vin.slice(index+1));
return boot;
}