有关二叉树的相关的问题的实现

#include "stdio.h"

#include "conio.h"

# include <stdlib.h>

typedef struct node

{

    struct node *lchild;

    struct node *rchild;

    char data;

}node,*bitree;

 

bitree CreateBitree()//创建二叉树

{   char a;

    bitree newtree;

    scanf("%c",&a);

    if(a == '#') return NULL;

    else

    {

        newtree = (bitree)malloc(sizeof(node));

        newtree->data = a;

        newtree->lchild = CreateBitree();

        newtree->rchild = CreateBitree();

    }

       return newtree;

}

 

int lcount(bitree bt)//接点的个数

{

    if(bt == NULL) return 0;

    else if(bt->lchild==NULL&&bt->rchild == NULL)

    return 1;

    else return (lcount(bt->lchild)+lcount(bt->rchild));

}

 

void Exchange(bitree bt)//交换左右结点

{

    bitree temp;

    if(bt)

    {

    Exchange(bt->lchild);

    Exchange(bt->rchild);

    temp = bt->lchild;

    bt->rchild = temp;

    bt->rchild = bt->lchild;

    bt->lchild = bt->rchild;

 

    }

}

 

int Ncount(bitree bt)//叶子结点的个数

{

    if(bt == NULL)

    return 0;

    else return (Ncount(bt->lchild)+Ncount(bt->rchild)+1);

}

 

void Preorder(bitree bt)//先序

{

    if(bt!=NULL)

    {

        printf("%c",bt->data);

        Preorder(bt->lchild);

        Preorder(bt->rchild);

    }

}

void Print(bitree bt)//输出

{

    if(bt!=NULL)

    {

        Print(bt->lchild);

        printf("%c",bt->data);

        Print(bt->rchild);

    }

}

 

bitree CopyBitree(bitree bt)//二叉树的复制

{

       bitree newlptr,newrptr,newnode;

       if(!bt) return NULL;

       else

       {

 

              newlptr = CopyBitree(bt->lchild);

              newrptr = CopyBitree(bt->rchild);

              newnode = (bitree)malloc(sizeof(bitree));

              newnode->data = bt->data;

              newnode->lchild = bt->lchild;

              newnode->rchild = bt->rchild;

       }

       return newnode;

}

int main()

{

    bitree root;

       int n,m;

       printf("-+a##*b##-c##d##/e##f##:/n");

    root = CreateBitree();

       Print(root);

    printf("the preorder is:/n");

    Preorder(root);

       Print(root);

       printf("/n");

       n = Ncount(root);

       printf("叶子结点的个数:%d",n);

  

       m = lcount( root);//接点的个数

 

       printf("/n");

       printf("结点的个数:%d",m);

       printf("/n");

 

       printf("左右二叉树交换后/n");

              Exchange(root);

       Print(root);

       printf("/n");

       printf("复制的二叉树:/n");

       CopyBitree(root);

       Print(root);

               printf("Hello, world/n");

       return 0;

   

}

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值