Establish binary linked list and traversal in preorder (chain stack non recursive)

Time:2022-1-5
#include<iostream>
using namespace std;
typedef struct BiNode{
    char data;
    struct BiNode *lchild,*rchild;
}BiTNode,*BiTree;
//Establish binary linked list first
void CreateBiTree(BiTree &T){    
    char ch;
    cin >> ch;
    if(ch=='#')  T=NULL;
    else{                            
        T=new BiTNode;
        T->data=ch;
        CreateBiTree(T->lchild);
        CreateBiTree(T->rchild);
    }
}
//Chain stack
typedef struct StackNode{
    BiTNode data;
    struct StackNode *next;
}StackNode,*LinkStack;
//Construct empty stack s
void InitStack(LinkStack &S){
    S=NULL;
}
bool StackEmpty(LinkStack S){
    if(!S)
        return true;
    return false;
}
//Stack 
void Push(LinkStack &S,BiTree e){
    StackNode *p=new StackNode;
    p->data=*e;
    p->next=S;
    S=p;
}
//Out of stack 
void Pop(LinkStack &S,BiTree e){
    if(S!=NULL){    
        *e=S->data;
        StackNode *p=S;
        S=S->next;
        delete p;
    }
} 
//Medium order traversal  
void In(BiTree T){ 
    LinkStack S; 
    BiTree p;
    BiTree q=new BiTNode;
    InitStack(S); p=T;
    while(p||!StackEmpty(S)){
        if(p){                            
            Push(S,p);                
            p=p->lchild;
        }       
        else{                             
            Pop(S,q);              
            cout<<q->data;
            p=q->rchild; 
        }
    }                                
}                                    
//Preorder traversal  
void Pre(BiTree T){ 
    LinkStack S; 
    BiTree p;
    BiTree q=new BiTNode;
    InitStack(S); p=T;
    while(p||!StackEmpty(S)){
        if(p){                            
            Push(S,p);
            cout<<p->data;                
            p=p->lchild;
        }       
        else{                             
            Pop(S,q);              
            p=q->rchild; 
        }
    }                                
}
int main(){
    BiTree tree;
    Cout < < "create binary linked list first:";
    CreateBiTree(tree);
    Cout < < "the result of preorder traversal is:"; 
    Pre(tree);
    cout<<endl;
    Cout < < "the result of middle order traversal is:";
    In(tree);
    cout<<endl;
}

Establish binary linked list and traversal in preorder (chain stack non recursive)