1. 树的存储
typedef struct BiTNode
{
char data;
struct BiTNode lchild,rchild;
}BTNode,*BTree;
2 .树的创建
void CreateTree(BTree &T)
{
char ch;
cin>>ch;
if(ch==‘#‘)
{
T=NULL;
}
else
{
T=(BTree) new BTNode;
if(!T)
exit(-1);
T->data=ch;
CreateTree(T->lchild);
CreateTree(T->rchild);
}
}
3.前序遍历
void PreOrder(BTree &T)
{
if(T)
{
cout<data;
PreOrder(T->lchild);
PreOrder(T->rchild);
}
}
4.中序遍历
void PreOrder(BTree &T)
{
if(T)
{
PreOrder(T->lchild);
cout<data;
PreOrder(T->rchild);
}
}
5.后序遍历
void PostOrder(BTree &T)
{
if(T!=NULL)
{
PostOrder(T->lchild);
PostOrder(T->rchild);
cout<data;
}
}
6. 完整代码
#include <stdlib.h>
#include
using namespace std;
typedef struct BiTNode
{
char data;
struct BiTNode lchild,rchild;
}BTNode,*BTree;
void CreateTree(BTree &T)
{
char ch;
cin>>ch;
if(ch==‘#‘)
{
T=NULL;
}
else
{
T=(BTree) new BTNode;
if(!T)
exit(-1);
T->data=ch;
CreateTree(T->lchild);
CreateTree(T->rchild);
}
}
void PreOrder(BTree &T)
{
if(T)
{
cout<data;
PreOrder(T->lchild);
PreOrder(T->rchild);
}
}
void InOrder(BTree &T)
{
if(T!=NULL)
{
InOrder(T->lchild);
cout<data;
InOrder(T->rchild);
}
void PostOrder(BTree &T)
{
if(T!=NULL)
{
PostOrder(T->lchild);
PostOrder(T->rchild);
cout<data;
}
}
int main()
{
BTree T;
cout<<"请输入树的节点:" ;
CreateTree(T);
cout<<"先序遍历:";
PreOrder(T) ;
cout<<endl;
cout<<"中序遍历:";
InOrder(T) ;
cout<<endl;
cout<<"后序遍历:";
PostOrder(T) ;
cout<<endl;
return 0;
}
7.输入样例
abd##e##cf###
8.运行截图
原文地址:https://www.cnblogs.com/singly/p/10797682.html