版权声明:转载商用请通知本人 https://blog.csdn.net/qq_41076577/article/details/83827598
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;
}