求二叉树的层次遍历

简介: 求二叉树的层次遍历

二叉树的层次遍历

Time Limit: 1000 ms Memory Limit: 65536 KiB

SubmitStatistic

Problem Description

已知一颗二叉树的前序遍历和中序遍历,求二叉树的层次遍历。

Input

输入数据有多组,输入T,代表有T组测试数据。每组数据有两个长度小于50的字符串,第一个字符串为前序遍历,第二个为中序遍历。

Output

每组输出这颗二叉树的层次遍历。

Sample Input

2

abc

bac

abdec

dbeac

Sample Output

abc

abcde

Hint

Source

fmh

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct node
{
    char data;
    struct node *lc, *rc;
};
struct node *creat(char a[], char b[], int n)//前序中序建立二叉树
{
    int i;
    if(n == 0)
    {
        return NULL;
    }
    struct node *root;
    root = (struct node *)malloc(sizeof(struct node));
    root->data = a[0];
    for(i = 0; i < n; i++)
    {
        if(b[i] == a[0])
        {
            break;
        }
    }
    root->lc = creat(a+1,b,i);
    root->rc = creat(a+i+1,b+1+i,n-1-i);
    return root;
};
void cengci(struct node *root)//求层次遍历的函数
{
    int out = 0, in = 0;
    struct node *q[100];
    q[in++] = root;
    while(in > out)
    {
        if(q[out] != 0)
        {
            printf("%c", q[out]->data);
            q[in++] = q[out]->lc;
            q[in++] = q[out]->rc;
        }
        out++;
    }
}
int main()
{
    int t, n;
    struct node *root;
    char a[1001], b[1001];
    scanf("%d", &t);
    while(t--)
    {
        scanf("%s %s", a, b);
        n = strlen(a);
        root = creat(a,b,n);
        cengci(root);
        printf("\n");
    }
    return 0;
}


相关文章
|
1月前
|
Python
二叉树前中后序遍历
这段内容是关于二叉树的前序、中序和后序遍历的Python实现。`Solution`类包含三个方法:`preorderTraversal`、`inorderTraversal`和`postorderTraversal`,分别返回二叉树节点值的前序、中序和后序遍历列表。每个方法都是递归的,遍历顺序为:前序(根-左-右)、中序(左-根-右)、后序(左-右-根)。
20 4
|
1月前
|
存储 算法 Java
二叉树层序遍历
二叉树层序遍历
18 0
|
1月前
|
算法
【二叉树】层序遍历
【二叉树】层序遍历
42 0
|
8月前
|
存储 C++
非递归遍历二叉树
非递归遍历二叉树
39 0
|
1月前
|
存储
详解二叉树的各种非递归遍历
详解二叉树的各种非递归遍历
|
1月前
|
存储
什么?二叉树的反前序遍历?
什么?二叉树的反前序遍历?
|
1月前
|
C++
二叉树的前序遍历(C++)
二叉树的前序遍历(C++)
31 0
二叉树的前序遍历(C++)
|
1月前
|
Linux
求二叉树的先序遍历
求二叉树的先序遍历
二叉树的层次遍历
层次遍历就是即逐层地,从左到右访问所有节点
二叉树的层次遍历