1. 程式人生 > >資料結構實驗之二叉樹五:層序遍歷 (sdut OJ 3344)

資料結構實驗之二叉樹五:層序遍歷 (sdut OJ 3344)

資料結構實驗之二叉樹五:層序遍歷

Time Limit: 1000ms   Memory limit: 65536K  有疑問?點這裡^_^

題目描述

已知一個按先序輸入的字元序列,如abd,,eg,,,cf,,,(其中,表示空結點)。請建立二叉樹並求二叉樹的層次遍歷序列。

輸入

 輸入資料有多行,第一行是一個整數t (t<1000),代表有t行測試資料。每行是一個長度小於50個字元的字串。

輸出

 輸出二叉樹的層次遍歷序列。

示例輸入

2
abd,,eg,,,cf,,,
xnl,,i,,u,,

示例輸出

abcdefg
xnuli

提示

來源

 xam

示例程式

#include <bits/stdc++.h>

using namespace std;

struct node
{
    char data;
    struct node *lchild, *rchild;
} *root;

int top;
int s = 0;
char st[55];
struct node *creat()
{
    struct node *root;
    if(st[top++] == ',')
        root = NULL;
    else
    {
        root = (struct node*)malloc(sizeof(struct node));
        root->data = st[top-1];
        root->lchild = creat();   //建立左子樹;
        root->rchild = creat();   //建立右子樹;
    }
    return root;
}

void Cengxu(struct node *root)
{
    queue<node *> q;   //建佇列
    if(root)
    {
        printf("%c", root->data);
        q.push(root);  //輸出根節點併入隊
    }

    while(! q.empty())
    {
        root = q.front();  //訪問隊首元素
        q.pop();           //刪除隊首(第一個頭根)
        if(root->lchild)
        {
            printf("%c", root->lchild->data); // 從此頭跟的左子樹,依次輸出
            q.push(root->lchild);
        }
         if(root->rchild)
        {
            printf("%c", root->rchild->data); // 從此頭跟的右子樹,依次輸出
            q.push(root->rchild);
        }
    }
}
int main()
{
    int t;
    scanf("%d", &t);
    while(t--)
    {
        scanf("%s", st);
        top = 0;
        root = creat();
        Cengxu(root);
        cout << endl;
    }
    return 0;
}