二叉树输入前序遍历,中序遍历重建二叉树并返回

 function reConstructBinaryTree(pre, vin)
        {
            if(pre.length===0||!pre){
                return;
            }
            var root = {
                val: pre[0]
            };
            var everyroot =vin.indexOf(pre[0]);
        root.left=reConstructBinaryTree(pre.slice(1,everyroot+1),vin.slice(0,everyroot));
            root.right=reConstructBinaryTree(pre.slice(everyroot+1),vin.slice(everyroot+1));
 
            return root;
        }
        console.log(reConstructBinaryTree('12473568','47215386'));

function reConstructBinaryTree(pre, vin)
{
    // write code here
    if(pre.length==0 || vin.length==0) return null;
    var index=vin.indexOf(pre[0]);
    var left=vin.slice(0,index);//中序左子树
    var right=vin.slice(index+1);//中序右子树
    return {
        val:pre[0],
        //递归左右子树的前序,中序 
        left:reConstructBinaryTree(pre.slice(1,index+1),left),
        right:reConstructBinaryTree(pre.slice(index+1),right)
     }; 
}

猜你喜欢

转载自blog.csdn.net/lizhengxv/article/details/82387674
今日推荐