//思路,先序遍历的第一个节点即为根节点,中序遍历根据根节点位置确认左右子树
//依次递归遍历,为空返回null
var buildTree = function(preorder, inorder) {
if(preorder.length === 0) return null;
const newVal = preorder[0];
const root = new TreeNode(newVal);
let i = 0;
for(; i < inorder.length; i++){
if(newVal === inorder[i]) break;
}
root.left = buildTree(preorder.slice(1,i+1),inorder.slice(0,i));
//注意这里为什么是i+1,js的slice函数返回从包含当前索引值下标往后的其余元素(下标从0开始)
//递归的是右子树,所以要+1
root.right = buildTree(preorder.slice(i+1),inorder.slice(i+1));
return root;
}
从前序与中序遍历序列构造二叉树
最新推荐文章于 2024-06-24 12:57:02 发布