题目:
输入二叉树的前序和中序遍历(且无重复数字),重建二叉树。
思路:
二叉树:val,left,right属性
递归,输入为数组,输出为treeNode节点
function reConstructTree(pre,mid){
if(!pre.length || !mid.length){
return null;
}
const rootVal = pre[0];
const node = new TreeNode(rootVal);
//i有两个含义,一个是遍历的中序下标;一个是中序左子树的节点个数
let i = 0;
for(;i<mid.length;i++){
if(mid[i] === rootVal){
break;
}
}
node.left = reConstructTree(pre.slice(1,i+1),mid.slice(0,i));
node.right = reConstructTree(pre.slice(i+1),mid.slice(i+1));
return node;
}