求大侠帮忙:先序非递归建立二叉树,然后中序非递归输出各节点。
#include<iostream>using namespace std;
struct binnode
{
char data;
binnode *lchild,*rchild;
};
typedef binnode *bintree;
struct seqstack
{
bintree data[100];
int top;
}s;
seqstack push(seqstack s,bintree x)
{
s.top++;
s.data [s.top ]=x;
return s;
}
seqstack pop(seqstack s)
{
s.top --;
return s;
}
bintree createtree() //先序输入
{
bool right = false;
bintree p,root;
seqstack s;
s.top=0;
char ch;
cin>>ch;
if(ch=='#')
root=NULL;
else
{
root=(binnode*)malloc(sizeof(bintree));
root->data=ch;
root->lchild=root->rchild=NULL;
push( s, root);
}
cin>>ch;
while(!(s.top==0)||ch!='#')
{
if(ch!='#'&& right == false)
{ p=root;
p=(binnode*)malloc(sizeof(bintree));
p->data=ch;
p->lchild=p->rchild=NULL;
root->lchild=p;
root=p;
push( s, root);
}
if (ch =='#')
{
pop( s);
right = true;
}
if (ch!='#'&& right == true)
{
p=(binnode *)malloc(sizeof(bintree));
p->data=ch;
p->lchild=p->rchild=NULL;
root->rchild=p;
root=p;
push( s, root);
right = false;
}
cin>>ch;
}
return root;
}
void inordertree(bintree t)
{
bintree p=t;
seqstack s;
s.top =0;
cout<<"output inorder root:"<<endl;
while(p||s.top >0)
{
if(p)
{
s.data [s.top ++]=p;
p=p->lchild ;
}
else
{
p=s.data [--s.top ];
cout<<p->data ;
p=p->rchild ;
}
}
cout<<endl;
}
void main()
{
bintree root;
cout<<"请先序输入各结点以建立二叉树:"<<endl;
root=createtree();
inordertree(root);
}