数据结构实验之二叉树七:叶子问题

来源:互联网 发布:2017网络热曲 编辑:程序博客网 时间:2024/06/05 03:50


这道题主要的思想就是按照先序遍历的结果建立二叉树,然后再用层次遍历,即可求得叶子的结点。

代码如下:

#include <stdio.h>
#include <malloc.h>
#include <string.h>
int len,i;
char a[55];
struct node{
    char 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 in,out;
    in=0;
    out=0;
    struct node *q[100];
    q[in++]=root;
    while(in>out){
        if(q[out]){
           if(q[out]->lchild==NULL&&q[out]->rchild==NULL)/*当前结点的左右子树都为空时,该结点就是叶子结点。*/
                printf("%c",q[out]->data);
           q[in++]=q[out]->lchild;
           q[in++]=q[out]->rchild;
        }
        out++;
    }
}
int main(){
    while(scanf("%s",a)!=EOF){
        i=0;
        len=strlen(a);
        struct node *root;
        root=Createtree();
        Cengci(root);
        printf("\n");
    }
    return 0;
}

0 0
原创粉丝点击