算法之路之征服上海交大的oj-1040. 二叉树层次遍历

/*

  1. 二叉树层次遍历
    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;
} 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值