树的三种遍历:
#include <iostream>
using namespace std;
typedef int DATA;
struct SNode//定义树的结构体
{
DATA data;
SNode *pLeft,*pRight;//左右子树
SNode (DATA d):data(d){
pLeft= NULL;
pRight= NULL;
}
};
SNode* g_pRoot = NULL; //定义根
void PreOrder(SNode *p){
cout<<p->data<<" ";
if(p->pLeft)
PreOrder(p->pLeft);
if(p->pRight)
PreOrder(p->pRight);
}
void InOrder(SNode* p){
if(p->pLeft){
InOrder(p->pLeft);
}
cout<<p->data<<" ";
if(p->pRight){
InOrder(p->pRight);
}
}
void PostOrder(SNode* p){
if(p->pLeft){
PostOrder(p->pLeft);
}
if(p->pRight){
PostOrder(p->pRight);
}
cout<<p->data<<" ";
}
void input(){
SNode *p = new SNode(30);
g_pRoot = p;
p ->pLeft = new SNode(40);
p ->pRight = new SNode(50);
SNode *p1 = p ->pLeft;
p1 ->pLeft = new SNode(70);
p1 ->pRight = new SNode(90);
SNode *p2 = p1 ->pLeft;
p2 ->pLeft = new SNode(55);
SNode *p3 = p1->pRight;
p3 ->pLeft = new SNode(25);
SNode *p4 = p ->pRight;
p4 ->pLeft = new SNode(60);
p4 ->pRight = new SNode(80);
}
int main(){
input();//引入数据
PreOrder(g_pRoot);//打印先序
cout<<endl;
InOrder(g_pRoot);//中序遍历
cout<<endl;
PostOrder(g_pRoot);//后序遍历
cout<<endl;
return 0;
}