- 原理图:
- 源程序代码:
- //PostOrderTraverse.cpp
- //This function is to postorder BiTree
- # include <malloc.h>
- # include <iostream>
- # include <conio.h>
- # define OK 1
- # define ERROR 0
- using namespace std;
- typedef char TElemType;
- typedef struct BiTNode //define structure BiTree
- { TElemType data;
- struct BiTNode *lchild,*rchild;
- }BiTNode, *BiTree;
- int CreateBiTree(BiTree &T) //createBiTree() sub-function
- { TElemType ch;
- cout<<"Please input data (/ for NULL node!) : ";
- cin>>ch;
- if(ch=='/') T=NULL;
- else
- { if(!(T=(BiTNode *)malloc(sizeof(BiTNode))))
- { cout<<"Overflow!"; //no alloction
- return (ERROR);
- }
- T->data=ch;
- CreateBiTree(T->lchild); //create lchild
- CreateBiTree(T->rchild); //create rchild
- }
- return (OK);
- } //CreateBiTree() end
- int PostOrderTraverse(BiTree T) //PostOrderTraverse() sub-function
- {
- if(T)
- { if (PostOrderTraverse(T->lchild)) //traverse lchild
- if(PostOrderTraverse(T->rchild)) //traverse rchild
- { cout<<T->data<<"->"; //visite T
- return (OK);
- }
- return (ERROR);
- }
- else
- return (OK);
- } //PostOrderTraverse() end
- int CentralOrderTraverse(BiTree T)
- {
- if(T)
- { if (CentralOrderTraverse(T->lchild)) //traverse lchild
- { cout<<T->data<<"->"; //visite T
- if(CentralOrderTraverse(T->rchild)) //traverse rchild
- return (OK);
- }
- return (ERROR);
- } //if end
- else
- return (OK);
- }
- int preOrderTraverse(BiTree T)
- {
- if(T)
- { cout<<T->data<<"->"; //visite T
- if (PostOrderTraverse(T->lchild)) //traverse lchild
- if(PostOrderTraverse(T->rchild))
- return OK; //traverse rchild
- return (ERROR);
- }
- else
- return (OK);
- }
- int main() //main() function
- { BiTree T;
- cout<<endl<<endl<<"PostOrderTraverse.cpp";
- cout<<endl<<"=========================";
- cout<<endl<<endl<<"Please input data to create BiTree:"<<endl;
- CreateBiTree(T); //call CreateBiTree
- std::cout<<"先序遍历:"<<endl;
- PostOrderTraverse(T);
- std::cout<<"中序遍历:"<<endl;
- CentralOrderTraverse(T);
- std::cout<<"后序遍历:"<<endl;
- preOrderTraverse(T);
- cout<<"End !"<<endl<<endl<<"...OK!...";
- getch();
- return 0;
- } //main()