#include<iostream> #include<stack> using namespace std; /*二叉树的前序遍历,按照 根节点->左孩子->右孩子 */ typedef struct node { char data; struct node *lchild,*rchild; }BinTree; void creatBinTree(BinTree * &root){ char ch; if(ch=getchar()){ if(ch=='#') root=NULL; else{ root=new BinTree; root->data=ch; creatBinTree(root->lchild); creatBinTree(root->rchild); } } } //创建二叉树, //递归遍历 void preOrder1(BinTree *&root){ //root是指向BinTree的结构体变量 if(root){ cout<<root->data<<" "; preOrder1(root->lchild); preOrder1(root->rchild); } } //非递归操作 void InOrder(BinTree * & root){ if(root){ InOrder(root->lchild); cout<<root->data<<" "; InOrder(root->rchild); } } void PostOrder(BinTree * &root){ if(root){ PostOrder(root->lchild); PostOrder(root->rchild); cout<<root->data<<" "; } } int main(){ BinTree * root; creatBinTree(root); cout<<"前序遍历:"; preOrder1(root); cout<<endl; cout<<"中序遍历:"; InOrder(root); cout<<endl; cout<<"后序遍历:"; PostOrder(root); cout<<endl; system("pause"); return 0; }
比如输入
AB##C##
前序:A B C
中序:B A C
后序:B C A