#include <iostream>
#include <string>
#include <list>
#include <sstream>
using namespace std;
//Define the tree node
struct NODE{
int nVal;
NODE *pL,*pR;
}const NullNode{0,0,0};
void Delete(NODE *pPar){
if(pPar!=NULL)
{
Delete(pPar->pL);
Delete(pPar->pR);
}
delete pPar;
}
NODE* AddNode(NODE*pPar,int nVal,const char *pPath){
if(pPar==0)
pPar=new NODE(NullNode);
switch(*pPath){
case ')': pPar->nVal=((pPar->nVal==0 && nVal!=0)?nVal:-1); break;
case 'L':pPar->pL=AddNode(pPar->pL,nVal,pPath+1);break;
case 'R':pPar->pR=AddNode(pPar->pR,nVal,pPath+1);break;
}//switch
return pPar;
}//AddNode
int main()
{
NODE *pRoot=0;
for(string strToken;cin>>strToken;){
int nVal=0;
const char *pStr=strToken.c_str(); //Get the point of string;
if(pStr[1]!=')')
{
for(;isdigit(*++pStr);nVal=nVal*10 + *pStr-'0');
if(*pStr!=',') while(true);
pRoot=AddNode(pRoot,nVal,++pStr);
continue;
}//if
list<NODE*> listNode(1,pRoot);
stringstream sstring;
for(list<NODE*>::iterator iter=listNode.begin();!listNode.empty();iter=(iter==listNode.end()?listNode.begin():iter)){
NODE *pTemp=*iter;
iter=listNode.erase(iter);
if(pTemp==0){ //it is Null
continue;
}
if(pTemp->nVal<=0){
listNode.clear();
sstring.str("");
break;
}
sstring<<pTemp->nVal<<' ';
iter=listNode.insert(iter,pTemp->pL),++iter;
iter=listNode.insert(iter,pTemp->pR),++iter;
}//for
Delete(pRoot);
pRoot=0;
strToken=sstring.str();
if(strToken.empty()){
strToken="not complete";
}
else{
strToken.erase(strToken.end()-1);
}
cout<<strToken<<endl;
}//for
return 0;
}
原文出处