二叉树的问题

lcftc 2003-02-11 09:20:47
我在学二叉树,很不明白,我写了八个小时了,可是总有错,哪位大哥帮忙看一下;
#include<iostream>
using namespace std;

//先序遍历
class TreeNode
{
public:
void CreateNode(TreeNode *);
void Print(TreeNode *);
private:
int data;
TreeNode *left,*right;
};



void TreeNode::CreateNode(TreeNode *p)
{
int x;
cin>>x;
if (x==0)
{
p=0;
return;
}
else
{
p->data=x;
TreeNode *ptr=new TreeNode;
ptr->left->CreateNode(p);
ptr->right->CreateNode(p);
}
}



void TreeNode::Print(TreeNode *p)
{
if (p!=0)
{
cout<<p->data<<" ";
Print(p->left);
Print(p->right);
}
else
cout<<0<<" ";
}


void main()
{
TreeNode root;
root.CreateNode(&root);
root.Print(&root);
}

输入1 2 0 0 3 0 0
要求输出1 2 0 0 3 0 0
0表示为空,也就是虚结点
...全文
89 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
lifanxi 2003-02-11
  • 打赏
  • 举报
回复
To liumingsky():
您一定像我一开始一样,没有调试就写下了回复。
if (x==0)
{
p=0;
return;
}
这里p=0有何意义?给型参赋值又不会影响实参的。
所以我在我改的程序中用了一个很别扭的指针的引用。
lifanxi 2003-02-11
  • 打赏
  • 举报
回复
这是顺着你思路写的程序:
太丑了,一看就是把C的程序硬搬到了C++中,进行了所谓的OO的封装,里面一点OO的思想也没体现出来。所以最好不要这样写程序。
另外这个程序还有内存泄露的问题,你得给它加个释放内存的函数。
#include<iostream>
using namespace std;

class TreeNode
{
public:
void CreateNode(TreeNode *& );
void Print(TreeNode *);
TreeNode() { left = right = 0; }
private:
int data;
TreeNode * left, * right;
};

void TreeNode::CreateNode(TreeNode * & p)
{
int x;
cin>>x;
if (x==0)
{
delete p;
p = 0;
return;
}
else
{

p->data=x;
p->left = new TreeNode;
p->left->CreateNode(p->left);
p->right = new TreeNode;
p->right->CreateNode(p->right);
}
}



void TreeNode::Print(TreeNode *p)
{
if (p!=0)
{
cout<<p->data<<" ";
Print(p->left);
Print(p->right);
}
else
cout<<0<<" ";
}


void main()
{
TreeNode * root = new TreeNode;
root->CreateNode(root);
root->Print(root);
}
liumingsky 2003-02-11
  • 打赏
  • 举报
回复
你的void TreeNode::CreateNode(TreeNode *p)写错了.
应该是:
void TreeNode::CreateNode(TreeNode *p)
{
int x;
cin>>x;
if (x==0)
{
p=0;
return;
}
else
{
p->data=x;
TreeNode *ptr=new TreeNode;
p->left=ptr;
p->left->CreateNode(p->left);
p->right=ptr;
p->right->CreateNode(p->right);
}
}
kinogre 2003-02-11
  • 打赏
  • 举报
回复
// 你该把你的错误结果告诉大家。
// 前后看了一两遍,没发现什么问题,如果有可能出在下面
void TreeNode::CreateNode(TreeNode *p)
{
int x;
cin>>x;
if (x==0)
{
p=0;
return;
}
else
{
p->data=x;
TreeNode *ptr=new TreeNode;
/* 下面这两句很可疑,因为
* TreeNode *ptr=new TreeNode;
* 只是初始化了ptr,但是它的两个孩子指针都没有初始化,
* 如果问题出在这里,你的结果应该是一些随机数,对不对?
* 你可以随意加一个错误,编译看看,应该有至少两个关于
* 以下两行的警告,解决方法可以是再用两个new语句。
*/
ptr->left->CreateNode(p);
ptr->right->CreateNode(p);
}
}
lifanxi 2003-02-11
  • 打赏
  • 举报
回复
你的程序错的可不是一点点呀,你可能还没有理清思路吧,我的脑子快被你的程序绕糊涂了。
等我想清楚了再给你回复。

70,034

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧