sicily 1156. Binary tree

#include<iostream> //给出一棵二叉树,输出前序遍历序列
#include<stack>
using namespace std;
struct node
{
char c;
int l,r;
}tree[
1010];
int vis[1010],rt[1010];
void add(int p,char c,int l,int r) //满足vis[p]==1且rt[p]==1 是根结点
{
tree[p].c
=c;
vis[p]
=1;
if(l>0)
{
tree[p].l
=l;vis[l]=1;rt[l]=0; //左右结点可以确定不是根结点
}
if(r>0)
{
tree[p].r
=r;vis[r]=1;rt[r]=0;
}
}
void preorder(int p)
{
cout
<<tree[p].c;
if(tree[p].l>0)
preorder(tree[p].l);
if(tree[p].r>0)
preorder(tree[p].r);

/*
stack<int> pre; //非递归前序遍历
pre.push(p);
while (!pre.empty())
{
int t=pre.top();
pre.pop();
cout<<tree[t].c;
if(tree[t].r>0)
pre.push(tree[t].r); //先压右子树入栈
if(tree[t].l>0)
pre.push(tree[t].l); //再压左子树入栈
}
*/

}
int main()
{
int n,p,l,r;
char c;
while(cin>>n)
{
for(int i=1;i<=1000;++i)
{
tree[i].l
=tree[i].r=0;
vis[i]
=0;
rt[i]
=1;
}
for(int i=1;i<=n;++i)
{
cin
>>p>>c>>l>>r;
add(p,c,l,r);
}
for(int i=1;i<=1000;++i)
if(vis[i]==1&&rt[i]==1)
{
preorder(i);
cout
<<endl;
break;
}
}
return 0;
}

posted on 2011-07-08 18:22  sysu_mjc  阅读(237)  评论(0编辑  收藏  举报

导航