您的位置:首页 > 其它

American Heritage USACO 3.4 (二叉树前序中序求后序)

2013-10-21 22:21 387 查看
就是根据二叉树的中序,前序,求后序,我想法是先求出二叉树再后序出来。开始感觉想起来很混乱,后来拿笔在纸上写一写就清楚很多了

这题不是很难,思路要清晰即可

/*

ID: hubiao cave

PROG: heritage

LANG: C++

*/

#include<iostream>

#include<fstream>

#include<string>

using namespace std;

string prestr,midstr;

struct node
{
char m;
node* left,*right;
node()
{
left=right=NULL;
}
};

node* groot;
ofstream fout("heritage.out");
node* GetChild(int ms,int me,int ps,int pe)
{
if(ms>me||ps>pe)
return NULL;
char parentch=prestr[ps];

int mark;
for(int i=ms;i<=me;i++)
if(midstr[i]==parentch)
{
mark=i;
break;
}

node* pnode=new node;
pnode->m=parentch;
pnode->left=GetChild(ms,mark-1,ps+1,ps+mark-ms);
pnode->right=GetChild(mark+1,me,ps+mark-ms+1,pe);
return pnode;

}

void AfterPrint(node* p)
{
if(p->left)
AfterPrint(p->left);
if(p->right)
AfterPrint(p->right);
fout<<p->m;
}

int main()

{

ifstream fin("heritage.in");

fin>>midstr>>prestr;
groot=new node;
groot->m=prestr[0];
int mark;
for(int i=0;i<midstr.length();i++)
{
if(midstr[i]==prestr[0])
mark=i;
}
groot->left=GetChild(0,mark-1,1,mark);
groot->right=GetChild(mark+1,midstr.length()-1,1+mark,prestr.length()-1);

AfterPrint(groot);
fout<<endl;

return 0;

}


留个影

USER: hubiao cave [cavehub1]
TASK: heritage
LANG: C++

Compiling...
Compile: OK

Executing...
Test 1: TEST OK [0.000 secs, 3500 KB]
Test 2: TEST OK [0.000 secs, 3500 KB]
Test 3: TEST OK [0.000 secs, 3500 KB]
Test 4: TEST OK [0.000 secs, 3500 KB]
Test 5: TEST OK [0.000 secs, 3500 KB]
Test 6: TEST OK [0.000 secs, 3500 KB]
Test 7: TEST OK [0.000 secs, 3500 KB]
Test 8: TEST OK [0.000 secs, 3500 KB]
Test 9: TEST OK [0.000 secs, 3500 KB]

All tests OK.

YOUR PROGRAM ('heritage') WORKED FIRST TIME! That's fantastic -- and a rare thing. Please accept these special automated congratulations.

Here are the te
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: