5.重构二叉树

5.重构二叉树

1.递归

        function TreeNode(value) {
            this.val = value;
            this.left = null;
            this.right = null;
        }
        var preOrder = []
        var inOrder = []
        var buildTree = function (preorder, inorder) {
            let map = new Map();
            for (let i = 0; i < inorder.length; i++) {
                map.set(inorder[i], i);
            }
            return fn(preorder, inorder, 0, preorder.length - 1, 0, inorder.length - 1, map);
        };

        function fn(preorder, inorder, preleft, preright, inleft, inright, map) {
            if (preleft > preright || inleft > inright) {
                return null;
            }
            let head = new node(preorder[preleft]);
            let index = map.get(preorder[preleft]);
            head.left = fn(preorder, inorder, preleft + 1, preleft + index - inleft, inleft, index - 1, map);
            head.right = fn(preorder, inorder, preleft + index - inleft + 1, preright, index + 1, inright, map);
            return head;

        }
        console.log(buildTree(preOrder, inOrder));

2.迭代

   <script>
        var buildTree = function (preorder, inorder) {
            if (preOrder.length === 0) {
                return null;
            }
            let stack = [];
            let root = new TreeNode(preorder[0]);
            stack.push(root);
            let inOrderIndex = 0;
            for (let preOrderIndex = 1; preOrderIndex < preorder.length; preOrderIndex++) {
                let preOrderValue = preorder[preOrderIndex];
                let node = stack[stack.length - 1];
                // preOrderValue 为左子节点
                if (node.val != inorder[inOrderIndex]) {
                    node.left = new TreeNode(preorder[preOrderIndex]);
                    stack.push(node.left);
                } else {
                    while (stack.length > 0 && stack[stack.length - 1].val == inorder[inOrderIndex]) {
                        node = stack.pop();
                        inOrderIndex++;
                    }
                    node.right = new TreeNode(preorder[preOrderIndex]);
                    stack.push(node.right);
                }
            }
            return root;
        };
        console.log(buildTree(preOrder, inOrder));
    </script>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值