思路:
1、从前序结果中取树根节点的内容
2、从中序遍历中找到根的位置pos,然后将中序数据分割成两部分
[ left , pos )和[ pos+1 , right ]
3、创建根节点。
递归创建根节点的左子树
递归创建根节点的右子树
class Solution {
int index=0;//index是为了从前序遍历中找根节点的位置
//preorder:前序遍历结果 inorder:中序遍历结果 [left,right]:标记树中节点在inorder中的范围
private TreeNode BuilidTree(int[] preorder,int[] inorder,int left,int right){
if(index >= preorder.length || left >= right){
return null;
}
//在中序遍历结果中找根的位置
//确认根节点的左右子树的区间
int rootIdx=left;
while(rootIdx<right){
if(preorder[index]==inorder[rootIdx]){
break;
}
rootIdx++;
}
//创建根节点
TreeNode root=new TreeNode(preorder[index]);
//递归创建根节点的左子树:[left,inrootIdx)
++index;
root.left=BuilidTree(preorder,inorder,left,rootIdx);
//递归创建根节点的右子树:[rootIdx+1,right]
root.right=BuilidTree(preorder,inorder,rootIdx+1,right);
return root;
}
public TreeNode buildTree(int[] preorder, int[] inorder) {
return BuilidTree(preorder,inorder,0,inorder.length);
}
}