一点心得

本文介绍了一种使用C++实现二叉树的方法,包括创建、打印和统计节点数等基本操作,并解决了递归过程中的死循环问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <iostream>
#include <stdlib.h>
#include<malloc.h>
  typedef struct tree{
   char data;
   struct tree *lchild,*rchild;
  }binode,*bitree;
  ///////////////////////////////
 
  void creat(bitree &t)
  { char c;
  cin>>c;
 // scanf("%c",&c);
   if(c=='r') t=NULL;
   else
    {if(!(t=(bitree)malloc(sizeof(tree))))   exit(0);
      t->data=c;
      creat(t->lchild);
      creat(t->rchild);
    }///////////else
  }///////////////////////creat
    
 ////////////////////////////////////////////////////////////////////////////////////////////////////////  
 
 
    void  print(bitree &t)
   {
     if(t)
    
     { cout<<t->data<<endl; 
    
       print(t->lchild);
    
       print(t->rchild);
       }
   
  
   }///////////////////print
 
///////////////////////////////////////////////////////////////////////////////////////////////////

 int root=0,lbranch=0,rbranch=0,leaf=0;/////////////////////SUM表示为结点总数///ROOT表示为根结点,RBRANCH和 LBRANCH分别表示为右左分支,///LEAF表示叶子结点
 
   void find(bitree t)
    {
       if(t)
        {      
         if(!(t->lchild)&&!(t->rchild))  {leaf++;find(t->lchild);}
            if(t->lchild&&t->rchild)    root++;
           if(t->lchild)     {lbranch++; find(t->lchild);}
           if(t->rchild)      {rbranch++; find(t->rchild);}
          }/////////////////////////////while
     
   
  cout<<"结点总数"<<rbranch+lbranch+1<<endl;
     cout<<"叶子结点"<<leaf<<endl;
     cout<<"根结点"<<root<<endl;

    }////////////////find
 

 

int main(int argc, char *argv[])
{bitree t;
 creat(t);
 print(t);

 find(t);
 
 
 system("PAUSE"); 
  return 0;
}
 

忙了那么久复算搞出来了,昨晚就建了个二叉树,然后输出。。。可是当中间的用于求各种结点的函数出现死循环时,找了半天也没出原因。第二天还是想着它错在哪,最糟糕的是居然忘了递归的最基本格式,把退出的if语句也忘了,感觉自己真的忘了好多原本已经属于自己的东西了,回首大学过去的一年里,还真算是虚度年华。。呜呜。。。还好,身边出现了很多很上进的朋友,尤其是这个学生大本营中,他们带给了我太多的信心和方向,努力了,学习我想学的东东。

评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值