【题目描述】
给定一个二叉树,请你以从根开始以层次遍历的顺序输出各个结点的编号。
【输入】
输入第一行一个整数n,表示有n个结点; 接下来输入n行每行三个数字,分别表示结点编号(0~n-1,0为根节点),父节点编号(-1表示无),左右子树(0左1右-1为根)。1≤n≤1000000。
【输出】
输出一行以空格分割的n个整数。
【输入样例】
7 0 -1 -1 1 0 0 3 0 1 2 1 0 4 1 1 5 2 0 6 2 1
【输出样例】
0 1 3 2 4 5 6
#include <bits/stdc++.h>
using namespace std;
int n, self, parent, tp, head;
struct Node
{
int id;
int parent;
int left;
int right;
};
queue <int> qu;
Node a[1000001];
int main()
{
cin >> n;
for(int i = 0; i < n; i++)
{
cin >> self >> parent >> tp;
a[self].id = self;
a[self].parent = parent;
a[self].left = -1;
a[self].right = -1;
if(parent != -1)
{
if(tp == 0) a[parent].left = self;
if(tp == 1) a[parent].right = self;
}
}
qu.push(0);
while(qu.empty() == false)
{
head = qu.front();
if(a[head].left != -1) qu.push(a[head].left);
if(a[head].right != -1) qu.push(a[head].right);
cout << head << " ";
qu.pop();
}
return 0;
}