1. 程式人生 > >二叉樹層序遍歷的c++寫法

二叉樹層序遍歷的c++寫法

void LevelOrder(struct node *root)//運用佇列(注意標頭檔案引用)
{
    queue<struct node*>q;
    struct node *p = root;
    if(p)
    {
        q.push(p);
    }
    while(!q.empty())
    {
        p = q.front();
        cout<<p->data;
        q.pop();
        if(p->lchild)
        {
            q.push(p->lchild);
        }
        if(p->rchild)
        {
            q.push(p->rchild);
        }
    }

}

例題選自PTA

5-10 樹的遍歷   (25分)

給定一棵二叉樹的後序遍歷和中序遍歷,請你輸出其層序遍歷的序列。這裡假設鍵值都是互不相等的正整數。

輸入格式:

輸入第一行給出一個正整數NNN≤30\le 3030),是二叉樹中結點的個數。第二行給出其後序遍歷序列。第三行給出其中序遍歷序列。數字間以空格分隔。

輸出格式:

在一行中輸出該樹的層序遍歷的序列。數字間以1個空格分隔,行首尾不得有多餘空格。

輸入樣例:

7
2 3 1 5 7 6 4
1 2 3 4 5 6 7

輸出樣例:

4 1 6 3 5 7 2
  • 時間限制:400ms
  • 記憶體限制:64MB
  • 程式碼長度限制:16kB

code:

#include<stdio.h>
#include<stdlib.h>
#include<iostream>
#include<queue>
using namespace std;
int c[40];
int ant;
struct node
{
    int data;
    struct node *lchild, *rchild;
};
struct node *rebuild(int a[], int b[], int n)
{
    struct node *root;
    int i;
    if(n==0) return NULL;
    root = (struct node*)malloc(sizeof(struct node));
    root->data = b[n-1];
    for(i = 0; i<n; i++)
    {
        if(a[i] == b[n-1]) break;
    }
    root->lchild = rebuild(a,b, i);
    root->rchild = rebuild(a+i+1, b+i, n-i-1);
    return root;
}
void LevelOrder(struct node *root)
{
    queue<struct node*>q;
    struct node *p = root;
    if(p)
    {
        q.push(p);
    }
    while(!q.empty())
    {
        p = q.front();
        c[ant++] = p->data;
        q.pop();
        if(p->lchild)
        {
            q.push(p->lchild);
        }
        if(p->rchild)
        {
            q.push(p->rchild);
        }
    }
}
int main()
{
    int n, i;
    ant = 0;
    int a[40], b[40];
    struct node *root;
    scanf("%d", &n);
    for(i = 0;i<n;i++)
    {
        scanf("%d", &a[i]);
    }
    for(i = 0;i<n;i++)
    {
        scanf("%d", &b[i]);
    }
    root = rebuild(b, a, n);
    LevelOrder(root);
    for(i = 0;i<ant;i++)
    {
        if(i==ant-1) printf("%d\n", c[i]);
        else printf("%d ", c[i]);
    }
}