Q:根据二叉树的前序和中序遍历结果重建二叉树
A:前序遍历的第一个节点是父节点,中序遍历中这个节点的左边即是该父节点的左子树,长度为lenLeft,右边就是该父节点的右子树,长度为lenRight。前序遍历中父节点右边lenLeft长度为左子树,再往右lenRight长度为右子树。
代码如下
static class Node
{
public int data;
public Node left;
public Node right;
}
public static Node create(int[] preArr,int[] midArr)
{
if (preArr==null||midArr==null||preArr.length==0||midArr.length==0)
{
return null;
}
return createHelper(preArr,0,preArr.length-1,midArr,0,midArr.length-1);
}
public static Node
createHelper(int[] preArr,int preStart,int preEnd,int[] midArr,int midStart,int midEnd)
{
Node root=new Node();
//根节点就是前序遍历中开头的节点
root.data=preArr[preStart];
if (preStart==preEnd)
{
if (midStart==midEnd&&preArr[preStart]==midArr[midStart])
{
return root;
}
else
{
throw new RuntimeException("input valid");
}
}
//找到中序遍历中根节点的位置:temp
int temp=midStart;
while (temp<=midEnd&&midArr[temp]!=preArr[preStart])
{
temp++;
}
if (temp>midEnd)
{
throw new RuntimeException("input valid");
}
int leftLen=temp-midStart;
if (leftLen>0)
{
root.left=createHelper(preArr,preStart+1,preStart+leftLen,midArr,midStart,temp-1);
}
if (leftLen<midEnd-midStart)
{
root.right=createHelper(preArr,preStart+leftLen+1,preEnd,midArr,temp+1,midEnd);
}
return root;
}
public static void main(String[] args)
{
int[] preArr={1,2,4,7,3,5,6,8};
int[] midArr={4,7,2,1,5,3,8,6};
Node t=create(preArr,midArr);
preOrder(t);
System.out.println();
midOrder(t);
System.out.println();
postOrder(t);
System.out.println();
doubleStackPostOrder(t);
}