首页 > 其他 > 详细

二叉树遍历的几种实现

时间:2019-10-09 21:39:13      阅读:112      评论:0      收藏:0      [点我收藏+]

用c++是实现的二叉树的存储以及几种遍历方法

 

 

#include<iostream>
#include<cstdlib>
#include<stack> //使用stl中的栈模板
using namespace std;

typedef struct BNode{ //定义节点的结构体
    char data;      //数据部分
    BNode* Lc;      //左孩子
    BNode* Rc;      //右孩子
}Bitree,*pBitree;

pBitree CreatTree(pBitree root){  //利用递归存树
    char c;
    cin>>c;//输入节点数据
    if(c!=#){
        root = (pBitree)malloc(sizeof(Bitree));
        root->data=c;
        root->Lc=CreatTree(root->Lc);
        root->Rc=CreatTree(root->Rc);
    }
    else
        root = NULL;
    return root;
}

void norecursionInorder1(pBitree root){ //不用递归的中序遍历1
    stack<pBitree> st;
    pBitree p;
    st.push(root);
    while(!st.empty()){
        while(st.top()!=NULL) {
            p=st.top();
            st.push(p->Lc);
        }
        st.pop();
        if(!st.empty()){
            p=st.top();
            st.pop();
            cout<<p->data;
            st.push(p->Rc); 
        }
    }
}

void norecursionInorder2(pBitree root){ //不用递归的中序遍历2
    stack<pBitree> st;
    pBitree p;
    p=root;
    while(p!=NULL||!st.empty()){
        if(p!=NULL){
            st.push(p);
            p=p->Lc;
        }
        else{
            p=st.top();
            cout<<p->data;
            st.pop();
            p=p->Rc;
        }
    }
}

void norecursionPreorder(pBitree root){ //不用递归的前序遍历
    stack<pBitree> st;
    pBitree p;
    p=root;
    while(p!=NULL||!st.empty()){
        if(p!=NULL){
            st.push(p);
            cout<<p->data;
            p=p->Lc;
        }
        else{
            p=st.top();
            st.pop();
            p=p->Rc;
        }
    }
}

void Preorder(pBitree root){
    if(root!=NULL){
        cout<<root->data;
        Preorder(root->Lc);
        Preorder(root->Rc);
    }
}

void Inorder(pBitree root){
    if(root!=NULL){
        Inorder(root->Lc);
        cout<<root->data;
        Inorder(root->Rc);
    }
}

void Postorder(pBitree root){
    if(root!=NULL){
        Postorder(root->Lc);
        Postorder(root->Rc);
        cout<<root->data;
    }
}

int main(){
    Bitree p;
    cout<<"Please input the datas:";
    pBitree root=CreatTree(&p); //初始话p为NULL
    CreatTree(root); //按中序遍历输入树,遇空节点补#  如测试数据ABD##EF###C###
    cout<<"Preorder :";
    Preorder(root);
    cout<<endl<<"Inorder  :";
    Inorder(root);
    cout<<endl<<"Psotorder:";
    Postorder(root);
    cout<<endl<<"norecursionPreorder:";
    norecursionPreorder(root);
    cout<<endl<<"norecursionInorder1:";
    norecursionInorder1(root);
    cout<<endl<<"norecursionInorder2:";
    norecursionInorder2(root);
    return 0;
}

 

 

输入测试数据 ABD##EF###C###

技术分享图片

 

二叉树遍历的几种实现

原文:https://www.cnblogs.com/r3t7rn/p/11644458.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!