码迷,mamicode.com
首页 > 其他好文 > 详细

二叉树的遍历(前、中、后、序,递归和非递归)

时间:2018-08-31 15:45:35      阅读:158      评论:0      收藏:0      [点我收藏+]

标签:font   while   node   oid   printf   style   evel   child   非递归   

一、二叉树的前序遍历:

//递归前序遍历 
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);
        }
    }
}

 

二叉树的遍历(前、中、后、序,递归和非递归)

标签:font   while   node   oid   printf   style   evel   child   非递归   

原文地址:https://www.cnblogs.com/hekuiFlye/p/9565904.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!