还是采取递归的思路。 找到找到每棵子树的根节点以及左子结点和右子结点的前序和中序集合.....对其递归调用本函数得到左子树和右子树,从而实现了当前子树的建立.....
由于前序序列首先访问根节点.....因而可以确定根节点.....对于前序和中序来说,始终都是最后才访问右子树.....因而在前序序列和中序序列中,右子树节点的长度和位置都是相同的;同样左子树也是连续分布且长度相同....
在前序序列中,分布为根节点->左子结点集合->右子结点集合
在中序序列中,分布为左子结点集合->根节点->右子结点集合
由于我们已经确定了根节点,因而可以很轻松的在中序序列中找到根节点的位置从而分隔出左子结点和右子结点的集合
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode buildTree(int[] preorder, int[] inorder) {
return fun(preorder,inorder);
}
TreeNode fun(int[] preorder,int[] inorder)
{
if(preorder.length==0)
{
return null;
}
TreeNode root = new TreeNode(preorder[0]);
int rootIndex = 0;
for(;rootIndex<inorder.length;rootIndex++)
{
if(inorder[rootIndex]==preorder[0])
{
break;
}
}
int[] preLeft = new int[rootIndex];
for(int i=1;i<=rootIndex;i++ )
{
preLeft[i-1] = preorder[i];
}
int[] preRight = new int[preorder.length-1-rootIndex];
for(int i=rootIndex+1;i<preorder.length;i++)
{
preRight[i-rootIndex-1] = preorder[i];
}
int[] inLeft = new int[rootIndex];
for(int i=0;i<rootIndex;i++ )
{
inLeft[i] = inorder[i];
}
int[] inRight = new int[inorder.length-1-rootIndex];
for(int i=rootIndex+1;i<inorder.length;i++)
{
inRight[i-rootIndex-1] = inorder[i];
}
root.left = fun(preLeft,inLeft);
root.right = fun(preRight,inRight);
return root;
}
}