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 BiNode
{
char data;
BiNode *lchild,*rchild;
};
BiNode *creat()
{
BiNode *root;
char ch;
cin>>ch;
if(ch=='#')
root=NULL;
else
{
root=new BiNode;
root->data=ch;
root->lchild=creat();
root->rchild=creat();
}
return root;
}
void Release(BiNode *root)
{
if(root!=NULL)
{
Release(root->lchild);
Release(root->rchild);
delete root;
}
}
void PreOrder1(BiNode *root)
{
if(root==NULL) return ;
else
{
PreOrder1(root->lchild);
if(root->lchild&&root->rchild)
{cout<<root->data;}
}
PreOrder1(root->rchild);
}
void PreOrder(BiNode *root)
{
if(root==NULL) return;
else
{
PreOrder(root->lchild);
PreOrder(root->rchild);
if(!root->lchild&&!root->rchild)
{cout<<root->data;}
}
}
int main()
{
int n;
cin>>n;
while(n--)
{
BiNode *root=creat();
PreOrder(root);
cout<<endl;
PreOrder1(root);
cout<<endl;
if(n!=0)
{
cout<<endl;
}
Release(root);
}
return 0;
}