思路:
对后序遍历结果从后向前进行遍历,其中每个值都是一个子树的根节点。用findNode(我用前序遍历)在tree中找到这个Node,将这个Node内的向量vct(中序遍历信息)拆分成左和右子树。
例:
Sample Input:
7
2 3 1 5 7 6 4
1 2 3 4 5 6 7
Sample Output:
4 1 6 3 5 7 2
#include<iostream>
#include<vector>
using namespace std;
struct Node
{
int value;
vector<int> vct;//
Node * lNode;//leftNode
Node * rNode;//rightNode
Node(int _value):value(_value),lNode(NULL),rNode(NULL){}//no use
Node():value(0),lNode(NULL),rNode(NULL){}
};
vector<int> PO;//postOrder
struct Node tree;//root node
Node * findNode(int n,Node * s)
//post Traversal the tree and scan the vector vct of the node
//n - looking for;s - start node
{
Node * np;//node pointer
if((*s).value!=0)
{
if(s->rNode!=NULL)
{
if((np=findNode(n,(*s).rNode))!=NULL)
{
return np;
}
}
if(s->lNode!=NULL)
{
if((np=findNode(n,(*s).lNode))!=NULL)
{
return np;
}
}
return NULL;
}
else
{
vector<int>::iterator it;
for(it=s->vct.begin();it!=s->vct.end();it++)
{
if((*it)==n)
{
return s;
}
}
return NULL;
}
return np;
}
int main()
{
//initialize & read data
int N;
cin>>N;
PO.resize(N);
for(int i=0;i<N;i++)
cin>>PO[i];
int tmp;
for(int i=0;i<N;i++)
{
cin>>tmp;
tree.vct.push_back(tmp);
}
tree.value=0;
//generate the tree
vector<int>::reverse_iterator rit;
Node * np;
for(rit=PO.rbegin();rit!=PO.rend();rit++)
{
np=findNode(*rit,&tree);
(*np).value=*rit;
bool pushToLeft=true;
vector<int> ::iterator it;
for(it=(*np).vct.begin();it!=(*np).vct.end();it++)
{
if(*it == *rit)
{
pushToLeft=false;
continue;
}
else
{
if(pushToLeft)
{
if((*np).lNode==NULL)
(*np).lNode=new Node();
(*np).lNode->vct.push_back(*it);
}
else
{
if((*np).rNode==NULL)
(*np).rNode=new Node();
(*np).rNode->vct.push_back(*it);
}
}
}
}
//output level order
vector<Node *> v1,v2;
vector<int > result;
v1.push_back(&tree);
while(!v1.empty())
{
for(int i=0;i<v1.size();i++)
{
result.push_back(v1[i]->value);
if(v1[i]->lNode!=NULL)
v2.push_back(v1[i]->lNode);
if(v1[i]->rNode!=NULL)
v2.push_back(v1[i]->rNode);
}
v1.clear();
v1.assign(v2.begin(),v2.end());
v2.clear();
}
for(int i=0;i<result.size()-1;i++)
cout<<result[i]<<" ";
cout<<result[result.size()-1];
return 0;
}