題目描述:
輸入某二叉樹的前序遍歷和中序遍歷的結果,請重建出該二叉樹。假設輸入的前序遍歷和中序遍歷的結果中都不含重復的數字。例如輸入前序遍歷序列{1,2,4,7,3,5,6,8}和中序遍歷序列{4,7,2,1,5,3,8,6},則重建二叉樹並返回根結點。
解題思路:
樹的遍歷有三種:分別是前序遍歷、中序遍歷、后序遍歷。本題是根據前序和中序遍歷序列重建二叉樹,我們可以通過一個具體的實例來發現規律,不難發現:前序遍歷序列的第一個數字就是樹的根結點。在中序遍歷序列中,可以掃描找到根結點的值,則左子樹的結點都位於根結點的左邊,右子樹的結點都位於根結點的右邊。
這樣,我們就通過這兩個序列找到了樹的根結點、左子樹結點和右子樹結點,接下來左右子樹的構建可以進一步通過遞歸來實現。
舉例:

編程實現(Java):
public TreeNode reConstructBinaryTree(int [] pre,int [] in) {
/*根據前序遍歷和中序遍歷確定一棵二叉樹*/
//遞歸實現
if(pre==null||in==null||pre.length==0)
return null;
return reConstructBinaryTree(pre,in,0,pre.length-1,0,in.length-1);
}
public TreeNode reConstructBinaryTree(int [] pre,int [] in,int pre_begin,
int pre_end,int in_begin,int in_end)
{
////前序序列:從pre_begin到pre_end, 中序序列:從in_begin到in_end
//遞歸結束條件
if(pre_begin>pre_end || in_begin>in_end)
return null;
int rootValue=pre[pre_begin];
TreeNode root=new TreeNode(rootValue); //第一個節點就是根節點
if(pre_begin==pre_end || in_begin==in_end)
return root;
//在中序序列中,找到root,前面的就是左子樹,右邊的就是右子樹
int rootIn=in_begin; //root在中序序列中的位置
while(rootIn<=in_end && in[rootIn]!=rootValue)
rootIn++;
int left_count=rootIn-in_begin; //左子樹節點個數
root.left=reConstructBinaryTree(pre,in,pre_begin+1,pre_begin+left_count,
in_begin,rootIn-1);
root.right=reConstructBinaryTree(pre,in,pre_begin+left_count+1,
pre_end,rootIn+1,in_end);
return root;
}