二叉树的问题
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表示为空,也就是虚结点