就是根据二叉树的中序,前序,求后序,我想法是先求出二叉树再后序出来。开始感觉想起来很混乱,后来拿笔在纸上写一写就清楚很多了
这题不是很难,思路要清晰即可
1 /* 2 3 ID: hubiao cave 4 5 PROG: heritage 6 7 LANG: C++ 8 9 */10 11 12 13 14 #include15 16 #include 17 18 #include 19 20 using namespace std;21 22 23 string prestr,midstr;24 25 struct node26 {27 char m;28 node* left,*right;29 node()30 {31 left=right=NULL;32 }33 };34 35 node* groot;36 ofstream fout("heritage.out");37 node* GetChild(int ms,int me,int ps,int pe)38 {39 if(ms>me||ps>pe)40 return NULL;41 char parentch=prestr[ps];42 43 int mark;44 for(int i=ms;i<=me;i++)45 if(midstr[i]==parentch)46 {47 mark=i;48 break;49 }50 51 node* pnode=new node;52 pnode->m=parentch;53 pnode->left=GetChild(ms,mark-1,ps+1,ps+mark-ms);54 pnode->right=GetChild(mark+1,me,ps+mark-ms+1,pe);55 return pnode;56 57 }58 59 void AfterPrint(node* p)60 {61 if(p->left)62 AfterPrint(p->left);63 if(p->right)64 AfterPrint(p->right);65 fout< m;66 }67 68 69 int main()70 71 {72 73 ifstream fin("heritage.in");74 75 76 77 fin>>midstr>>prestr;78 groot=new node;79 groot->m=prestr[0];80 int mark;81 for(int i=0;i left=GetChild(0,mark-1,1,mark);87 groot->right=GetChild(mark+1,midstr.length()-1,1+mark,prestr.length()-1);88 89 AfterPrint(groot);90 fout<
留个影
USER: hubiao cave [cavehub1]TASK: heritageLANG: C++Compiling...Compile: OKExecuting... 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