SDUT_2137_數據結構實驗之求二叉樹後序遍歷和層次遍歷

Problem Description

已知一棵二叉樹的前序遍歷和中序遍歷,求二叉樹的後序遍歷和層序遍歷。

Input

輸入數據有多組,第一行是一個整數t (t<1000),代表有t組測試數據。每組包括兩個長度小於50 的字符串,第一個字符串表示二叉樹的先序遍歷序列,第二個字符串表示二叉樹的中序遍歷序列。

Output

每組第一行輸出二叉樹的後序遍歷序列,第二行輸出二叉樹的層次遍歷序列。

Example Input

2
abdegcf
dbgeafc
xnliu
lnixu

Example Output

dgebfca
abcdefg
linux
xnuli

代碼

#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
#include <algorithm>
using namespace std;
char pre[55],in[55];
 struct Node
{
    int data;
    struct Node *lchild;
    struct Node *rchild;
};
//返回構造的二叉樹的根
Node *CreatTree(char *pre,char *in,int n)
{
    Node *p;
    char *q;
    int k;
    if(n <= 0)
        return NULL;
    p = (Node *)malloc(sizeof(Node));
    p->data = *pre;//i
    for(q=in;q<in+n;q++)
    {
        if(*q == *pre)
            break;
    }
    k = q-in;
    p->lchild = CreatTree(pre+1,in,k);
    p->rchild = CreatTree(pre+k+1,q+1,n-k-1);
    return p;
}
//後序遍歷
void PostOrder(Node *b)
{
    if(b!=NULL)
    {
        PostOrder(b->lchild);
        PostOrder(b->rchild);
        printf("%c",b->data);
    }
}
//層次遍歷(用隊列完成)
void levelOrder(Node *b)
{
    queue<struct Node *> Q;
    Q.push(b);   //現將節點入隊
    while(!Q.empty())  //隊列不爲空時循環
    {
        Node *t;
        t = Q.front();  //隊頭元素
        if(t)
        {
            Q.push(t->lchild);  //向隊列中添加元素t->lchild(順序的將樹的節點一個個入隊)
            Q.push(t->rchild);  //向隊列中添加元素t->rchild
            printf("%c",t->data);  //輸出當前的節點
        }
        Q.pop();  //從隊列中取出並刪除元素
    }
}

int main()
{
    int T;
    int len;
    scanf("%d",&T);
    while(T--)
    {
        scanf("%s",pre);
        len = strlen(pre);
        scanf("%s",in);
        Node *b = CreatTree(pre,in,len);
        //後序遍歷
        PostOrder(b);
        printf("\n");
        //層序遍歷
        levelOrder(b);
        printf("\n");
    }
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章