统计二叉树中的叶子结点数

建立二叉链表,统计二叉树中的叶子结点数并输出。

按照完全二叉树的形式输入二叉树的各结点数据(字符),其中虚结点用'@'表示。输入以'#'结束。

输出叶子结点的个数及具体值。第一行为为叶子结点的数据值,各数据用空格分隔,第二行为叶子结点的个数。

输入示例:

abc@@de#

输出:

b d e
3

 

部分代码可能有点多余。。。。反正能用

#include<stdio.h>
#include<stdlib.h> 
#include<string.h>
typedef struct stu{
    char data;
    struct stu *lc,*rc;
}bitree;
bitree *creat(){
    char ch;
    bitree *q[100];//设置指针型数组构建队列 
    int front,rear;
    bitree *root,*s;
    root=NULL;
    front=1,rear=0;
    while((ch=getchar())!='#'){
        s=NULL;
        if(ch!='@'){
            s=(bitree*)malloc(sizeof(bitree));
            s->data=ch;
            s->lc=NULL;
            s->rc=NULL;
        }
        rear++;
        q[rear]=s;
        if(rear==1)root=s;
        else{
            if(s&&q[front]){
                if(rear%2==0)q[front]->lc=s;
                else q[front]->rc=s;
            }
            if(rear%2==1)front++;
            
        }
    }
    return root;
}//建立二叉树 
void order(bitree *root){
    if(root!=NULL){
    if(root->lc==NULL&&root->rc==NULL){
        printf("%c ",root->data);}    
    order(root->lc);//递归 
    
    order(root->rc);
        
    }
    
}//遍历二叉树 ,找到叶子 
void num(bitree *root){
    bitree *q[100];
    bitree *s;
    int rear=1,front=0;
    int n=0;
    q[rear]=root;
    while(front<rear){
        front++;
        s=q[front];
    if(s->lc==NULL&&s->rc==NULL){
        n++;
    }
    if(s->lc!=NULL){
        rear++;
        q[rear]=s->lc;
    }
    if(s->rc!=NULL){
        rear++;
        q[rear]=s->rc;
    }    
    }
    printf("\n%d",n);
    
}//广度优先遍历,得出叶子个数 
int main()
{
    bitree *root;
    root=creat();
    order(root);
    num(root);
    return 0;
}

posted on 2020-05-08 21:06  allons10  阅读(554)  评论(0)    收藏  举报