二叉树遍历的几种实现

試著忘記壹切 提交于 2019-11-30 23:22:38

用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;
    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<<"nostackPreorder:";
    norecursionPreorder(root);
    cout<<endl<<"nostackInorder1:";
    norecursionInorder1(root);
    cout<<endl<<"nostackInorder2:";
    norecursionInorder2(root);
    return 0;
}

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

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!