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 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看