题目描述:
根据一棵树的前序遍历与中序遍历构造二叉树。
注意:
你可以假设树中没有重复的元素。
例如,给出
前序遍历 preorder = [3,9,20,15,7]
中序遍历 inorder = [9,3,15,20,7]
返回如下的二叉树:
3
/ \
9 20
/ \
15 7
思路分析:
废话不多说,直接来想思路,首先思考,根节点应该做什么。
类似上一题,我们肯定要想办法确定根节点的值,把根节点做出来,然后递归构造左右子树即可。(都是套路)
具体思路可参照公众号文章https://mp.weixin.qq.com/s/OlpaDhPDTJlQ5MJ8tsARlA
class Solution {
public TreeNode buildTree(int[] preorder, int[] inorder) {
return build(preorder,0,preorder.length-1,
inorder,0,inorder.length-1);
}
TreeNode build(int[] preorder,int prestart,int preend,
int[] inorder,int instart,int inend){
if(prestart>preend){
return null;
}
int rootVal=preorder[prestart];
int index=0;
for(int i=instart;i<=inend;i++){
if(inorder[i]==rootVal){
index=i;
break;
}
}
int leftsize=index-instart;
TreeNode root=new TreeNode(rootVal);
root.left=build(preorder,prestart+1,prestart+leftsize,
inorder,instart,index-1);
root.right=build(preorder,prestart+leftsize+1,preend,
inorder,index+1,inend);
return root;
}
}