欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

数据结构实验之二叉树五:层序遍历 (SDUT 3344)

程序员文章站 2022-05-20 10:34:44
...
#include <bits/stdc++.h>
using namespace std;
struct node
{
    char data;
    struct node *lc, *rc;
};
char s[505];
int num;
struct node *creat()
{
    struct node *root;
    if(s[num ++] == ',')
    {
        root = NULL;
    }
    else
    {
        root = new node;
        root -> data = s[num - 1];
        root -> lc = creat();
        root -> rc = creat();
    }
    return root;
};
void level(struct node *root)
{
       struct node *q[100];
       int in = 0, out = 0;
       q[in++] = root;
       while(out < in)
       {
           if(q[out])
           {
               printf("%c", q[out] -> data);
               q[in++] = q[out] -> lc;
               q[in++] = q[out] -> rc;
           }
           out++;

       }
}
int main()
{
    int t;
    scanf("%d",&t);
    while(t--)
    {
        scanf("%s",s);
        num = 0;
        struct node *root;
        root = creat();
        level(root);
        printf("\n");
    }
    return 0;
}


 

相关标签: 层次遍历