m0_74203003 2023-02-27 22:07 采纳率: 85.7%
浏览 20
已结题

C++我创建了一个类描述二叉树,但是析构时内存报错,能帮我看看怎么回事吗?

C++我创建了一个类描述二叉树,但是析构时内存报错,能帮我看看怎么回事吗?

#ifndef BTREE_H_
#define BTREE_H_

#include<iostream>

using namespace std;

struct bintree
{
  char ch;
  bintree * ltree;
  bintree * rtree;
};
  

class bt
{
  private:
  bintree *root;
  public:
  bt(char c = 'A');
  bintree *rroot();
  void insert(bintree * b);
  void presearch(bintree * b);
  void insearch(bintree * b);
  void nexsearch(bintree * b);
  void return_ad(bintree *b);
  ~bt();
  
};











#endif



#include"btree.h"


bt::bt(char c)
{
  root = new bintree;
  root->ch = c;
  
}


bintree * bt::rroot(){return root;}


void bt::insert(bintree * b) 
{
cout<< "The node "<< b->ch<<" has a left node ? "<<endl;
char choice;
cin>>choice;
if(choice == 'Y')
{
  bintree * i = new bintree;
  cout<<"Please enter the content of left node : "<< endl;
  cin>>choice;
  b->ltree = i;
  i->ch =choice;
  insert(i);
}
else
  b->ltree = NULL;

cout<< "The node "<< b->ch<<" has a right node ?"<<endl;
cin>>choice;
if(choice == 'Y')
{
  bintree * j= new bintree;
  cout<<"Please enter the content of right node : "<< endl;
  cin>>choice;
  b->rtree = j;
  j->ch =choice;
  insert(j);
}
else
  b->rtree = NULL;
}


void bt::presearch(bintree * tree)
{
  if(tree)
{
  cout<<" "<<tree->ch<<" ";
  presearch(tree->ltree);
  presearch(tree->rtree);
}
} 

void bt::insearch(bintree * tree)
{
  if(tree)
{
    insearch(tree->ltree);
    cout<<" "<<tree->ch<<" ";
    insearch(tree->rtree);
}
}

void bt::nexsearch(bintree * tree)
{
  if(tree)
{
    nexsearch(tree->ltree);
    nexsearch(tree->rtree);
    cout<<" "<<tree->ch<<" ";
 
}
}

void bt::delete_tree(bintree * tree)
{
  if(tree)
  {
  delete_tree(tree->ltree);
  delete_tree(tree->ltree);
  delete tree;
  }
 }


bt::~bt()
{
delete_tree(root);
}
  • 写回答

1条回答 默认 最新

  • 小果沐雨 2023-02-28 08:57
    关注

    delete_tree(tree->ltree);调两次,你准备薅秃它

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

问题事件

  • 系统已结题 3月8日
  • 已采纳回答 2月28日
  • 创建了问题 2月27日

悬赏问题

  • ¥15 mmocr的训练错误,结果全为0
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀