建立二叉树,并遍历。
#include<iostream>
using namespace std;
struct BiNode
{
char data;
BiNode *lchild,*rchild;
};
class BiTree
{
public:
BiTree(BiNode *root) //有参构造函数,初始化一颗二叉树。
{
root=Creat();
}
~BiTree(); //析构函数,释放二叉树
void PreOrder(BiNode *root); //前序遍历
void InOrder(BiNode *root); //中序遍历
void PostOrder(BiNode *root); //后序遍历
private:
BiNode *root;
BiNode *Creat() //有参函数调用
{
char ch;
cin>>ch;
if(ch=='#') root=NULL;
else{
root=new BiNode;
root->data=ch;
root->lchild=Creat();
root->rchild=Creat();
}
}
void Release(BiNode *root); //析构函数调用
};
void BiTree::PreOrder(BiNode *root) //qian
{
if(root==NULL) return;
else{
cout<<root->data;
PreOrder(root->lchild);
PreOrder(root->rchild);
}
}
void BiTree::InOrder(BiNode *root) //zhong
{
if(root==NULL) return;
else{
InOrder(root->lchild);
cout<<root->data;
InOrder(root->rchild);
}
}
void BiTree::PostOrder(BiNode *root) //hou
{
if(root==NULL) return;
else{
PostOrder(root->lchild);
PostOrder(root->rchild);
cout<<root->data;
}
}
int main()
{
cout<<"请输入二叉树的序列"<<endl;
BiTree::BiTree(root);
cout<<"二叉树的遍历结果为:"<<endl;
BiTree::PreOrder(root);
cout<<"*****"<<endl;
BiTree::InOrder(root);
cout<<"*****"<<endl;
BiTree::PostOrder(root);
return 0;
}
搞了一天了, 还是没弄出来。
#include<iostream>
using namespace std;
struct BiNode
{
char data;
BiNode *lchild,*rchild;
};
class BiTree
{
public:
BiTree(BiNode *root) //有参构造函数,初始化一颗二叉树。
{
root=Creat();
}
~BiTree(); //析构函数,释放二叉树
void PreOrder(BiNode *root); //前序遍历
void InOrder(BiNode *root); //中序遍历
void PostOrder(BiNode *root); //后序遍历
private:
BiNode *root;
BiNode *Creat() //有参函数调用
{
char ch;
cin>>ch;
if(ch=='#') root=NULL;
else{
root=new BiNode;
root->data=ch;
root->lchild=Creat();
root->rchild=Creat();
}
}
void Release(BiNode *root); //析构函数调用
};
void BiTree::PreOrder(BiNode *root) //qian
{
if(root==NULL) return;
else{
cout<<root->data;
PreOrder(root->lchild);
PreOrder(root->rchild);
}
}
void BiTree::InOrder(BiNode *root) //zhong
{
if(root==NULL) return;
else{
InOrder(root->lchild);
cout<<root->data;
InOrder(root->rchild);
}
}
void BiTree::PostOrder(BiNode *root) //hou
{
if(root==NULL) return;
else{
PostOrder(root->lchild);
PostOrder(root->rchild);
cout<<root->data;
}
}
int main()
{
cout<<"请输入二叉树的序列"<<endl;
BiTree::BiTree(root);
cout<<"二叉树的遍历结果为:"<<endl;
BiTree::PreOrder(root);
cout<<"*****"<<endl;
BiTree::InOrder(root);
cout<<"*****"<<endl;
BiTree::PostOrder(root);
return 0;
}
搞了一天了, 还是没弄出来。