Description
Input
Input may contain several test data sets.
For each test data set, first comes one integer n (1 <= n <= 1000) in one line representing the number of nodes in the tree. Then n lines follow, each of them contains information of one tree node. One line consist of four members in order: i (integer, represents the identifier of this node, 1 <= i <= 1000, unique in this test data set), c (char, represents the content of this node described as above, ‘A’ <= c <= ‘Z’), l (integer, represents the identifier of the left child of this node, 0 <= l <= 1000, note that when l is 0 it means that there is no left child of this node), r (integer, represents the identifier of the right child of this node, 0 <= r <= 1000, note that when r is 0 it means that there is no right child of this node). These four members are separated by one space.
Input is ended by EOF.
You can assume that all inputs are valid. All nodes can form only one valid binary tree in every test data set.
Output
Sample Input
34 C 1 31 A 0 03 B 0 011000 Z 0 031 Q 0 22 W 3 03 Q 0 0
Sample Output
CABZQWQ
#include <bits/stdc++.h>
using namespace std;
typedef struct node
{
char value;
int l,r;
}node;
node nod[1005];
bool isroot[1005];
int inde[1005];
int n;
void preorder(node root)
{
cout<<root.value;
if(root.l!=0)
{
preorder(nod[root.l]);
}
if(root.r!=0)
{
preorder(nod[root.r]);
}
}
int main()
{
while(cin>>n)
{
memset(isroot,1,sizeof(isroot));
for(int i=0;i<n;i++)
{
int tem;
cin>>tem;
inde[i]=tem;
cin>>nod[tem].value>>nod[tem].l>>nod[tem].r ;
isroot[nod[tem].r ]=0;
isroot[nod[tem].l ]=0;
}
for(int i=0;i<n;i++)
{
if(isroot[inde[i]])
{
preorder(nod[inde[i]]);
}
}
cout<<endl;
}
return 0;
}
这道题用inde数组记录每个结点的编号。通过inde数组去访问isroot数组,跟nod数组。
不是每一道跟树有关的题都要建树,可以通过数组转换。