1040. 二叉树层次遍历

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 <queue>
using namespace std;


int main()
{
    int n;
    cin>>n;
    int tree[2*n]={0};
    for(int i=1;i<n;i++){
        int t=0;
        cin>>t;
        if(tree[2*t]==0)tree[2*t]=i;
        else tree[2*t+1]=i;
    }
    queue<int> q;
    q.push(0);
    while(!q.empty()){
        int now=q.front();
        q.pop();
        cout<<now<<' ';
        if(tree[2*now])q.push(tree[2*now]);
        if(tree[2*now+1])q.push(tree[2*now+1]);
    }
    return 0;
}
原文地址:https://www.cnblogs.com/bernieloveslife/p/8046532.html