分别采用递归和非递归方式编写两个函数,求一棵二叉树中叶子节点个数

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/KevinWu93/article/details/41534983

分别采用递归和非递归方式编写两个函数,求一棵二叉树中叶子节点个数

#include 
#include 
#define MAXSIZE 50

typedef char datatype;
typedef struct node
{
    datatype data;
    struct node *lchild,*rchild;
} bintnode,*bintree;

//用来存放非递归统计叶节点的根节点
typedef struct
{
    bintree a[MAXSIZE];
    int top;
} stack;

void inputbint(bintree *root)
{
    datatype in;
    scanf("%c",&in);
    if(in=='#')
    {
        *root=NULL;
        return;
    }
    *root=(bintree)malloc(sizeof(bintnode));
    if(*root==NULL)return;
    (*root)->data=in;
    inputbint(&(*root)->lchild);
    inputbint(&(*root)->rchild);
    return;
}

//前序遍历
void printbint(bintree root)
{
    if(root==NULL)return;
    else
    {
        printf("%c",root->data);
        printbint(root->lchild);
        printbint(root->rchild);
    }
}

void recursion(bintree root,int *l)
{
    if (root!=NULL)
    {
        if ((root->lchild==NULL)&&root->rchild==NULL)
        {
            (*l)++;
        }
        recursion(root->lchild,l);
        recursion(root->rchild,l);
        return;
    }
    return;
}

int unrecursion(bintree root)
{
    int l=0;
    stack s;
    s.top=0;
    do
    {
        if(root!=NULL)
        {
            s.a[s.top]=root;
            s.top++;
            root=root->lchild;
        }
        else
        {
            s.top--;
            root=s.a[s.top];
            if(root->lchild==NULL&&root->rchild==NULL)
            {
                l++;
            }
            root=root->rchild;
        }
    }
    while(s.top!=0||root!=NULL);
    return l;
}

int main()
{
    int l=0;//记录叶子节点个数
    bintree root;
    printf("请输入二叉树,子节点为空请输#:\n");
    inputbint(&root);
    printbint(root);
    recursion(root,&l);//递归实现
    printf("\n(递归实现)叶子节点的个数为:%d\n",l);
    l=0;
    l=unrecursion(root);//非递归实现
    printf("\n(非递归实现)叶子节点的个数为:%d",l);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/KevinWu93/article/details/41534983