读书人

二叉树的遍历解决方法

发布时间: 2012-04-07 17:31:50 作者: rapoo

二叉树的遍历
#include "iostream"
using namespace std;

struct BiNode
{
char data;
BiNode *lchild,*rchild;
};

class BiTree
{
public:
BiTree() {root=NULL;}
BiTree (BiNode *root);
~BiTree();
//~BiTree(BiNode *root);
void PreOrder(BiNode *root);
void InOrder (BiNode *root);
void PostOrder (BiNode *root);
void LeveOrder (BiNode *root);
void Create(BiNode *root);
private:
BiNode *root;

void Release(BiNode *root);
};

BiTree::BiTree(BiNode *root)
{
Create(root);
}
/*二叉树的建立*/
void BiTree::Create(BiNode *root)
{
char ch;
cin>>ch;
if (ch=='#')
{
root=NULL;
}
else
{
root=new BiNode;
root->data=ch;
Create(root->lchild);
Create(root->rchild);
}
}
/*前序遍历*/
void BiTree::PreOrder(BiNode *root)
{
if (root==NULL)
{
return;
}
else
{
cout<<root->data;
PreOrder(root->lchild);
PreOrder(root->rchild);
}
}
/*中序遍历*/
void BiTree::InOrder(BiNode *root)
{
if (root==NULL)
{
return;
}
else
{
InOrder(root->lchild);
cout<<root->data;
InOrder(root->rchild);
}
}
/*后序遍历*/
void BiTree::PostOrder(BiNode *root)
{
if (root==NULL)
{
return;
}
else
{
PostOrder(root->lchild);
PostOrder(root->rchild);
cout<<root->data;
}
}
/*层序遍历*/
void BiTree::LeveOrder(BiNode *root)
{
int front,rear;
BiNode *array[10],*q;
if (root==NULL)
{
return;
}
front=rear=0;
array[++rear]=root;
while (front!=rear)
{
q=array[++front];
cout<<q->data;
if (q->lchild!=NULL)
{
array[++rear]=q->lchild;
}
if (q->rchild!=NULL)
{
array[++rear]=q->rchild;
}
}
}
BiTree::~BiTree()
{
Release(root);
}
void BiTree::Release(BiNode *root)
{
if (root!=NULL)
{
Release(root->lchild);
Release(root->rchild);
delete root;
}
}
int main()
{
BiNode *p=NULL;
BiTree object;
object.Create(p);
object.PreOrder(p);
object.InOrder(p);
object.PostOrder(p);
object.LeveOrder(p);
return 0;
}


没有什么东西输出来,调试过发现p和root指针都只是局部变量,求解怎么让他输出来

[解决办法]
C++的话可以使用指针的引用
C语言的话,可以使用指针的指针
或者给插入函数添加一个返回值,返回根节点
[解决办法]
建议用按地址传递

读书人网 >C++

热点推荐