版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/OscaronMar/article/details/82432861
/*
- 二叉树层次遍历
Description
给出一棵二叉树,求它的层次遍历结果。
[二叉树的遍历问题是一种精神,务必领会]
Input Format
第一行,N<1000000,表示二叉树节点数。
默认序号为0的节点为树根。接下来共N-1行,
依次表示序号为1,…,N-1的节点的父亲节点序号。
如果一个节点有两个孩子节点,左孩子节点序号总是小于右孩子节点序号。
Output Format
仅一行,二叉树的层次遍历结果。节点序号间用空格隔开。
Hint
Sample Input
6
0
1
1
0
4
Sample Output
0 1 4 2 3 5
*/
#include<iostream>
#include<vector>
#include<queue>
#include<string.h>
using namespace std;
const int MAXN = 1000005;
vector<int> G[MAXN];
int n;
queue<int> q;
bool vis[MAXN];
void addEdge(int a,int b){
G[b].push_back(a); //建立树的过程
}
int main(){
cin>>n;
memset(vis,false,sizeof(vis));
for(int i=1;i<n;i++){
int t;
cin>>t;
addEdge(i,t);
}
q.push(0);
vis[0] = true;
cout<<0<<" ";
while(!q.empty()){
int u = q.front();
q.pop();
for(int i=0;i<G[u].size();i++){
int v = G[u][i];
if(!vis[v]){
q.push(v);
vis[v] = true;
cout<<v<<" ";
}
}
}
return 0;
}