( 实现二叉树生成问题 夹带 内存泄露问题)这些代码怎么了析构函数调用了吗 到最后 msdos竟然不能打开了
( 实现二叉树生成问题 夹带 内存泄露问题)这些代码怎么了析构函数调用了吗 到最后 msdos竟然不能打开了
目的: 用类作为二叉树的结点 生成一个 有序(无论前序还是后序)二叉树 二叉树有类成员函数可以控制
……
下边是 一段糟糕的代码 ;
怎样优化它……
#include <iostream>
using namespace std;
int cunt=0;// 跟踪 创建的实例
class tree
{
public:
tree()
{
cout << " \tcreat tree : " << (++cunt) << endl;
data='0';
childl=NULL;
childr=NULL;
}
tree(tree &tr)
{
cout << " \t\tcreat copy tree : "<<(++cunt)<<endl;
tree CopyTr;
CopyTr.data = tr.data;
CopyTr.childl=tr.childl;
CopyTr.childr=tr.childr;
}
~tree()
{
cout << " \t del tree : " << (--cunt) <<endl;
delete childl;
delete childr;
}
void CreatTree( tree *p)
{
char ch;
cout << "input data : " ;
cin >> ch;
if(!cin.good())
{
cout << " \tchar error ! ";
exit(0);
}
if (!(ch == 'q'))
{
childl = new tree;
childr = new tree;
if((childl==NULL)|(childr==NULL))
{
cout<< " \t\t\t mem error ! ";
}
p->data=ch;
CreatTree (p->childl);
CreatTree (p->childr);
}
else
p=NULL;
}
void DisplayData( const tree *a)
{
cout << " the node data is : " << a->data;
}
private:
char data;
tree *childl;
tree *childr;
};
int main(int argc, char* argv[])
{
tree * a;
// a = new tree; 若加上会出现死循环!
a->CreatTree(a);
a->DisplayData(a);
return 0;
}