问题来源
问题链接:https://leetcode-cn.com/problems/zhong-jian-er-cha-shu-lcof/
分析
我们是用递归来解决的,根据前序遍历和中序遍历的特点我们主要分为两个步骤:
- 用前序遍历找根(定义一个索引preIndex遍历前序遍历的数组)
- new一个新节点将其此时posIndex索引指向的值保存起来(构建树)
- 用中序遍历找根的左子树和根的右子树(写一个finVal函数用于在中序遍历中找到前序遍历索引指向的元素,然后返回在中序遍历数组的索引index,index左边为其左子树,右边为其右子树)
- 递归调用函数创建其左子树和右子树(不过注意条件的更新)
下面结合图片来理解一下
AC代码
class Solution {
public int preIndex=0;
//遍历前序遍历数组 递归构建二叉树
public TreeNode buildTreeChild(int[] preorder,int[] inorder, int begin,int end){
if(begin>end) {
return null;
}
TreeNode root=new TreeNode(preorder[preIndex]);
int index=findVal(inorder,preorder[preIndex],begin,end);
preIndex++;
//更新条件
root.left=buildTreeChild(preorder,inorder,begin,index-1);
root.right=buildTreeChild(preorder,inorder,index+1,end);
return root;
}
//在中序遍历中找对应的值
public int findVal(int[] inorder,int key,int begin,int end){
for(int i=begin;i<=end;i++)
{
if(inorder[i]==key)
{
return i;
}
}
return -1;
}
public TreeNode buildTree(int[] preorder, int[] inorder) {
if(preorder==null||inorder==null) return null;
return buildTreeChild(preorder,inorder,0,inorder.length-1);
}
}
总结:中序遍历和后续遍历创建二叉树和本题类似,只不过索引从后续遍历数组从后往前遍历罢了,注意没有前序遍历后续遍历创建二叉树。