数据结构实验四

本文介绍了一个简单的二叉树类的实现,包括创建二叉树、遍历节点、计算节点数量、查找最大深度等基本功能,并提供了源代码及运行结果。

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

源代码

  1. #include  
  2. using namespace std;  
  3.   
  4. class BiTree      
  5. {      
  6. public:      
  7.     BiTree(){memset(Tree,0,sizeof(Tree));}      
  8.     ~BiTree(){}      
  9.     int createbitree();    
  10.     int visit(int n);    
  11.     int calnode(int i,int &n);      
  12.     int depth(int n);      
  13.     int max(int a,int b);   
  14.     int parent();  
  15.     int children();  
  16.     void leaves();  
  17.     int leavesnode();  
  18. private:  
  19.     int Tree[100];      
  20. };      
  21.   
  22.   
  23. int BiTree::createbitree()      
  24. {     
  25.     int n,i=1;     
  26.     cout<<"请按照从上到下的顺序依次输入二叉树各个节点,空节点用0表示,以-1表示输入结束:"<>n && n!=-1)     
  27.     {    
  28.         Tree[i]=n;    
  29.         i++;    
  30.     }    
  31.     return 0;    
  32. }   
  33.      
  34.   
  35. int BiTree::visit(int n)      
  36. {   
  37.     for(n=1;n<100;n++)  
  38.     {  
  39.     if(Tree[n]!=-1 && Tree[n]!=0)    
  40.         cout<>x;  
  41.     for(n=1;n<100;n++)  
  42.     {  
  43.         if(Tree[n]==x)  
  44.             cout<<"双亲:"<>x;  
  45.     for(n=1;n<100;n++)  
  46.     {  
  47.         if(Tree[n]==x)  
  48.         {  
  49.             if(Tree[2*n]!=0 && Tree[2*n+1]!=0)  
  50.                 cout<<"左孩子:"<b?a:b;  
  51. }  
  52.   
  53.   
  54. int BiTree::depth(int n)  
  55. {  
  56.     int hl,hr;  
  57.     for(n=1;n<100;)  
  58.     {  
  59.         if (Tree[n]!=-1)   
  60.         {  
  61.             hl = depth(2*n);  
  62.             hr = depth(2*n+1);  
  63.         }     
  64.     }  
  65.     return 1+ max(hl, hr);  
  66. }  
  67.   
  68.   
  69. int main()      
  70. {  
  71.   
  72.     BiTree tree;      
  73.     int n=0;   
  74.       
  75.     tree.createbitree();   
  76.     cout<  

运行结果


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值