何大土  

一、二叉树的前序遍历:

//递归前序遍历 
void preorder(BTNode *root){
    if(root){
        printf("%c ",root->data);
        preorder(root->lchild);
        preorder(root->rchild);
    }
}

//非递归前序遍历 
void pre(BTNode *root){
    stack <BTNode*>s;    
    if(root)
        s.push(root);
    BTNode *p;
    while(!s.empty()){
        p=s.top();
        s.pop();
        printf("%c ",p->data);
        if(p->rchild!=NULL)
            s.push(p->rchild);
        if(p->lchild!=NULL)
            s.push(p->lchild);
    }
}

二、二叉树的中序遍历:

//递归中序遍历 
void inorder(BTNode *root){
    if(root){
        inorder(root->lchild);
        printf("%c ",root->data);
        inorder(root->rchild);
    }
}

//非递归中序遍历
void in(BTNode *root){
    stack<BTNode*> s;
    if(root){
        BTNode *p=root;
        while(!s.empty()||p){
            while(p){
                s.push(p);
                p=p->lchild;
            }
            if(!s.empty()){
                p=s.top();
                s.pop();
                printf("%c ",p->data);
                p=p->rchild;                
            }
        }
    }
}

三、二叉树的后序遍历:

//递归后序遍历
void postorder(BTNode *root){
    if(root!=NULL){
        postorder(root->lchild);
        postorder(root->rchild);
        printf("%c ",root->data);
    }
} 

//非递归后序遍历
void post(BTNode *root){
    stack<BTNode*> s;
    if(root!=NULL){
        BTNode *p=root;
        do{
            while(p!=NULL){
                s.push(p);
                p=p->lchild;
            }
            int flag=1;
            BTNode *q=NULL;
            while(!s.empty()&&flag){
                p=s.top();
                if(p->rchild==q){
                    printf("%c ",p->data);
                    s.pop();
                    q=p;
                }else{
                    p=p->rchild;
                    flag=0;                    
                }
            }
        }while(!s.empty());
        printf("\n");
    }
} 

四、二叉树的层次遍历:

//层次遍历 
void levelorder(BTNode *root){
    if(root!=NULL){
        queue<BTNode*> q;
        q.push(root);
        BTNode *p;
        while(!q.empty()){
            p=q.front();
            q.pop();
            printf("%c ",p->data);
            if(p->lchild!=NULL)
                q.push(p->lchild);
            if(p->rchild!=NULL)
                q.push(p->rchild);
        }
    }
}

 

posted on 2018-08-31 15:05  何大土  阅读(3306)  评论(0编辑  收藏  举报