重构二叉树的思路: 前序遍历(根,左,右)的第一个数必定是根节点
中序遍历(左,根,右)的根节点左边是左子树,右边是右子树
因此,在前序遍历数组中得出根节点,然后在中序遍历数组中找到根节点,
然后将左子树与右子树的前序遍历数组与中序遍历数组得出,分别返回左右子树的根节点,赋给根节点的左右结点
依次迭代直到最后一个叶子(左右结点都为空)
class TreeNode{
int val;
TreeNode left;
TreeNode right;
TreeNode(int x)
{
val = x;
}
}
public TreeNode reConstructBinaryTree(int [] pre,int [] in) {
if(pre == null || in == null || pre.length == 0|| in.length ==0)
{
return null;
}
TreeNode node = new TreeNode(pre[0]);
int rootIndex = 0;
int leftLength =0;
int rightLength=0;
int i =0;
while(i< in.length )
{
if(in[i] == root)
{
rootIndex = i;
leftLength = i;
rightLength = in.length - i-1;
break;
}
i++;
}
if(leftLength >0)
{
int[] leftTree = new int[leftLength];
int[] leftPre = new int[leftLength];
for(int j =0;j< rootIndex;j++)
{
leftTree[j] = in[j];
leftPre[j] = pre[j+1];
}
node.left =reConstructBinaryTree(leftPre,leftTree);
}
if(rightLength >0)
{
int[] rightTree = new int[rightLength];
int[] rightPre = new int[rightLength];
for(int j = 0; j< rightTree.length ;j++)
{
rightTree[j] = in[rootIndex+1 +j];
rightPre[j] = pre[rootIndex+1 +j];
}
node.right = reConstructBinaryTree(rightPre,rightTree);
}
return node;
}
}