二叉树的创建及基本操作(三种递归遍历算法和非递归中序遍历算法,统计二叉树的叶子结点及求二叉树的深度)

二叉树的创建及基本操作
内容:
1.利用二叉树的二叉链表存储方法按照先序遍历序列创建二叉树,实现三种递归遍历算法。

2.编写统计二叉树的叶子结点及求二叉树深度的算法(可用递归方法)。

3.实现二叉树的非递归中序遍历算法。

二叉链表存储表示:

typedef struct BiTNode{
   

  TElemType  data;

  struct BiTNode  *lchild, *rchild;

} BiTNode,*BiTree;

算法设计及程序源代码

  1. 二叉树的创建算法(按先序遍历序列创建):
BiTree creatbitree(){
   

BiTree T;

TElemType ch;

scanf("%c",&ch);

if(ch=='#') T=NULL;//#代表空格字符

else{
   

T=(BiTNode*)malloc(sizeof(BiTNode));

T->data=ch;//生成根结点

T->lchild=creatbitree();//生成左子树

T->rchild=creatbitree();//生成右子树

}

return T;    }

2.统计二叉树叶子结点个数的算法:

int countleaf(BiTree T,int count) {
   

   if(T){
   

      if((T->lchild==NULL)&&(T->rchild==NULL))

      count++;

      count=countleaf(T->lchild,count);

      count=countleaf(T->rchild,count);}

   return count;}   

3.求二叉树深度的算法:

int bitreedepth(BiTree T) {
   

   int leftdepth,rightdepth,maxdepth;

   if(T!=NULL){
   

   leftdepth=bitreedepth(T->lchild) ;//左子树深度

   rightdepth=bitreedepth(T->rchild) ;//右子树深度

   maxdepth=leftdepth>rightdepth?leftdepth:rightdepth;//取最大深度

   return maxdepth+1;}

   else return 0; }

4.先序、中序、后序递归遍历算法:

先序:


void preorder(BiTree T) {
   

   if(T!=NULL){
   

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

      preorder
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值