<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
//前序遍历 preorder=[3,9,20,15,7]
//中序遍历 inorder=[9,3,15,20,7]
var BuildeTree = function(preOrder, inOrder) {
let map = new Map()
for (let i = 0; i < inOrder.length; i++) {
map.set(inOrder[i], i)
}
return helper(preOrder, 0, preOrder.length - 1, inOrder, 0, inOrder.length - 1, map)
}
function helper(preorder, p_start, p_end, inorder, i_start, i_end, map) {
if (p_start > p_end) {
return null
}
let rootVal = preorder[p_start]
let root = new TreeNode(rootVal)
let mid = map.get(rootVal)
let leftNum = mid - i_start
let leftNum = mid - i_start
root.left = helper(preorder, p_start + 1, p_start + leftNum, inorder, i_start, mid - 1, map);
root.right = helper(preorder, p_start + leftNum, p_end, inorder, mid + 1, map)
return root
}
</script>
</body>
</html>