1156. Binary tree
限制条件
时间限制: 1 秒, 内存限制: 32 兆
题目描述
Your task is very simple: Given a binary tree, every node of which contains one upper case character (‘A’ to ‘Z’); you just need to print all characters of this tree in pre-order.
输入格式
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.
输出格式
For every test data set, please traverse the given tree and print the content of each node in pre-order. Characters should be printed in one line without any separating space.
样例输入
3
4 C 1 3
1 A 0 0
3 B 0 0
1
1000 Z 0 0
3
1 Q 0 2
2 W 3 0
3 Q 0 0
样例输出
CAB
Z
QWQ
题目来源
ZSUACM Team Member
这道题大概意思就是要你输出一颗二叉树的前序就行了,题目有多个测试样例,第一行输入为n(1<=n<=1000),剩下有n行,每行分别为i(节点的序号,1<=i<=1000,整形),c(节点的字符,'A'<=c<='Z',char类型),l,r(分别为左子数和右子数的序号,1<=l,r<=1000)。
这道题的关键点是找到树根:没有出现在左子树和右子树处的数字即为数根的序号
//1156. Binary tree
//2016.11.23
#include <iostream>
#include <cstring>
using namespace std;
struct Node
{
char data;
int lchild;
int rchild;
bool flag; //标记是否是树根
};
Node n[1005];
int a[1005];
void p(int x) //深搜
{
if(x==0)
return;
else
{
cout<<n[x].data;
p(n[x].lchild);
p(n[x].rchild);
}
}
int main()
{
int m,k;
while(cin>>m)
{
for(int i=1;i<=m;i++)
{
cin>>k;
a[i]=k;
cin>>n[k].data>>n[k].lchild>>n[k].rchild;
n[k].flag = true;
}
for(int i=1;i<=m;i++) // 将左右子树 出现的数对应节点标记
{
n[n[a[i]].lchild].flag = false;
n[n[a[i]].rchild].flag = false;
}
int cnt;
for(int i=1;i<=m;i++) //找出根
{
if(n[a[i]].flag ==true)
cnt=a[i];
}
p(cnt);
cout<<endl;
}
return 0;
}