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];
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>