Problem:
Given preorder and inorder traversal of a tree, construct the binary tree.
Explanation:
将前序遍历和中序遍历还原成二叉树
My Thinking:
My Solution:
Optimum Thinking:
preorder的第一个数一定是根,在inorder中找到它的位置index,左半边的数构成左子树,右半边的数构成右子树,它的左孩子是preorder中它后一个数,右孩子应该是它往后移左子树个数+1位的数。
Optimum Solution:
class Solution {
public TreeNode buildTree(int[] preorder, int[] inorder) {
return build(0,0,inorder.length-1,preorder,inorder);
}
public TreeNode build(int prestart,int instart,int inend,int[] preorder, int[] inorder){
if(prestart>=preorder.length || instart>inend)
return null;
TreeNode root=new TreeNode(preorder[prestart]);
//寻找prestart在inorder中的位置
int index=0;
for(int i=0;i<inorder.length;i++){
if(preorder[prestart]==inorder[i]){
index=i;
break;
}
}
//对inorder中index两边的数字进行递归
root.left=build(prestart+1,instart,index-1,preorder,inorder);
//inorder中index左边有index个数,因此当前结点的右孩子应该在preorder中往后移index+1位
root.right=build(prestart+index-instart+1,index+1,inend,preorder,inorder);
return root;
}
}