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

来源:互联网 发布:淘宝直通车一天烧50万 编辑:程序博客网 时间:2024/05/22 05:57


这道题的算法思想就是:按照先序遍历的顺序建立一个二叉树,然后利用结构体数组进行层次遍历,层次遍历时,注意要把每个结点的左右结点存入结构体数组。

代码如下:

#include <stdio.h>
#include <malloc.h>
#include <string.h>
char a[55];
int len,i;
struct node{
    int data;
    struct node* lchild,*rchild;
};
struct node* Createtree(){
    struct node* root;
    if(i<len){
        char c=a[i++];
        if(c==',')
            return NULL;
        else{
            root=(struct node*)malloc(sizeof(struct node));
            root->data=c;
            root->lchild=Createtree();
            root->rchild=Createtree();
        }
    }
    return root;
};
void Cengci(struct node* root){/*层次遍历函数*/
    int left,out;
    struct node *q[100];
    left=0;
    out=0;
    q[left++]=root;
    while(left>out){
        if(q[out]){
            printf("%c",q[out]->data);
            q[left++]=q[out]->lchild;//每次指定当前结点的左子树,将其存入结构体数组中;
            q[left++]=q[out]->rchild;//每次指定当前结点的右子树,将其存入结构体数组中;
        }
        out++;
    }
}
int main(){
    int t;
    scanf("%d",&t);
    while(t--){
        struct node* root;
        scanf("%s",a);
        len=strlen(a);
        i=0;
        root=Createtree();
        Cengci(root);
        if(t>=1)
            printf("\n");
    }
    return 0;
}

0 0
原创粉丝点击