#include <iostream>
#include <stack>
using namespace std;
struct node{
node *left;
node *right;
char value;
};
class CBiTree{
private:
node *root;
void visit(node *n);
void CreateBitree(node **r);
void DestroyBitree(node *r);
public:
CBiTree();
~CBiTree();
void preorder();
void inorder();
void postorder();
};
CBiTree::CBiTree(){
CreateBitree(&root);
}
CBiTree::~CBiTree(){
DestroyBitree(root);
}
void CBiTree::CreateBitree(node **r){
char ch;
cin>>ch;
if('.'==ch){
*r=NULL;
}
else
{
*r=new node;
(*r)->value=ch;
CreateBitree(&((*r)->left));
CreateBitree(&((*r)->right));
}
}
void CBiTree::DestroyBitree(node *r){
if(r!=NULL){
DestroyBitree(r->left);
DestroyBitree(r->right);
delete r;
}
}
void CBiTree::visit(node *n){
cout<<n->value<<" ";
}
void CBiTree::preorder(){
stack<node*> st;
node *p=root;
while(p!=NULL||!st.empty()){
if(p!=NULL){
visit(p);
st.push(p);
p=p->left;
}
else{
p=st.top();st.pop();
p=p->right;
}
}
}
void CBiTree::inorder(){
stack<node*> st;
node *p=root;
while(p!=NULL||!st.empty()){
if(p!=NULL){
st.push(p);
p=p->left;
}
else{
p=st.top();st.pop();
visit(p);
p=p->right;
}
}
}
void CBiTree::postorder(){
stack<node*> st;
node *p=root,*q=NULL;
while(p!=NULL||!st.empty()){
if(p!=NULL){
st.push(p);
p=p->left;
}
else{
p=st.top();
if(p->right==NULL||p->right==q){
visit(p);
q=p;
st.pop();
p=NULL;
}
else{
p=p->right;
}
}
}
}
int main(){
freopen("test.in","r",stdin);
freopen("test.out","w",stdout);
int n;
cin>>n;
while(n-->0){
CBiTree *t=new CBiTree;
cout<<"preorder:";t->preorder();cout<<endl;
cout<<"inorder:";t->inorder();cout<<endl;
cout<<"postorder:";t->postorder();cout<<endl;
delete t;
}
return 0;
}
二叉树非递归遍历(前序、中序、后序)
最新推荐文章于 2024-09-21 19:25:16 发布