1001:二叉樹的操作——遍歷2
阿新 • • 發佈:2018-11-25
1001:二叉樹的操作——遍歷2
Time/Memory Limit:1000 MS/32768 K
Submitted: 69 Accepted: 47
Problem Description
按照給定的擴充套件二叉樹前序遍歷序列建立相應的非空二叉樹,要求採用二叉連結串列進行儲存表示,並按中序次序列印葉子結點,按後序次序列印度為2的分支結點。
Input
第一行為一個整數n,表示以下有n組資料,每組資料佔一行,為擴充套件二叉樹的前序遍歷序列。
Output
每組輸出佔兩行,葉子結點和分支結點各佔一行,每兩組輸出之間有一換行。
Sample Input
3 AB#D##C## AB##C#D## ABD##E##C#F##
Sample Output
DC A BD A DEF BA
#include<iostream> using namespace std; struct Node{ char data; Node *lc,*rc; }; class Tree{ public: Node *root; Tree(){root=creat(root);} void InOrder(Node *p){ if(p==NULL) return; else { InOrder(p->lc); if(!p->lc&&!p->rc) cout<<p->data; InOrder(p->rc); } } void PostOrder(Node *p){ if(p!=NULL) { PostOrder(p->lc); PostOrder(p->rc); if(p->lc!=NULL&&p->rc!=NULL) { cout<<p->data; } } return; } private: Node *creat(Node *p){ char ch; cin>>ch; if(ch=='#') return NULL; else{ Node *p=new Node;p->data=ch; p->lc=creat(p->lc); p->rc=creat(p->rc); return p; } } }; int main(){ int n, flag=0; while(cin>>n){ while(n--){ Tree t; if(flag!=0) cout<<endl; flag++; t.InOrder(t.root); cout<<endl; t.PostOrder(t.root); cout<<endl; } } return 0; }