劍指offer----重建二叉樹
阿新 • • 發佈:2019-02-08
題目描述
輸入某二叉樹的前序遍歷和中序遍歷的結果,請重建出該二叉樹。假設輸入的前序遍歷和中序遍歷的結果中都不含重複的數字。例如輸入前序遍歷序列{1,2,4,7,3,5,6,8}和中序遍歷序列{4,7,2,1,5,3,8,6},則重建二叉樹並返回。
//get_vec返回一個根據索引分割的陣列,包括vec[begin]和vec[end]。
vector<int> get_vec(vector<int>&vec,int begin,int end)
{
vector<int> res;
for(int i=begin;i>=0 &&i<=end;++i)//begin可能大於end也可能小於
//0,此時應該返回空陣列
{
res.push_back(vec[i]);
}
return res;
}
TreeNode* reConstructBinaryTree(vector<int> pre,vector<int> vin) {
if(pre.size()==0)return NULL;//子樹為空,返回NULL
TreeNode* root=new TreeNode(pre[0]);
int root_int_vin=0;
while(pre[0]!=vin[root_int_vin])
{
root_int_vin++;//尋找根在中序遍歷中的位置,
//很明顯,根的左邊為左子樹,右邊為右子樹
}
/*
不管是前序遍歷或者中序遍歷,右子樹始終是在最後訪問的,
所以可以分割出來根,左子樹右子樹。
{1,2,4,7,3,5,6,8},根為1,左子樹{2,4,7},右子樹{3,5,6,8}。
{4,7,2,1,5,3,8,6},左子樹{4,7,2},根為1,右子樹{5,3,8,6}。
*/
//遞迴呼叫,從上到下建立二叉樹
root->left=reConstructBinaryTree(get_vec(pre,1,root_int_vin),get_vec(vin,0,root_int_vin-1));
root->right=reConstructBinaryTree(get_vec(pre,root_int_vin+1,pre.size()-1),get_vec(vin,root_int_vin+1,pre.size()-1));
return root;
}