Given preorder and inorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
从前序遍历数组和中序遍历数组 ,得到二叉树。
我直接做没有想出思路,看了大牛的博客 http://blog.youkuaiyun.com/fightforyourdream/article/details/16914595 的代码才理解了意思。虽然有点事后诸葛,但是应该这样考虑。
a 首先应该拿出具体的例子来看,比如 preorder 1,2,4,5,3 inorder 4,2,5,1,3
b 肯定是用递归来做,那么肯定是对root来做
c 发现preorder中root就是第一个元素,相应的在inorder中,root把其他元素分成两半,一半是root.left,一半是root.right
d 能够想到上面那步,代码也就能写出来了。
public class Solution {
public TreeNode buildTree(int[] preorder, int[] inorder) {
if(preorder.length==0||inorder.length==0||preorder.length!=inorder.length){
return null;
}
int n = preorder.length;
return useme(preorder,inorder,0,n-1,0,n-1);
}
public TreeNode useme(int[] preorder,int[] inorder, int prestart,int preend,int instart,int inend){
TreeNode root = new TreeNode(preorder[prestart]);
int rootIndex;
for(rootIndex=instart;rootIndex<inend;rootIndex++){
if(inorder[rootIndex]==preorder[prestart]){
break;
}
}
int len = rootIndex - instart;
if(rootIndex>instart){
root.left = useme(preorder,inorder,prestart+1,prestart+len,instart,rootIndex-1);
}
if(rootIndex<inend){
root.right = useme(preorder,inorder,prestart+len+1,preend,rootIndex+1,inend);
}
return root;
}
}