[数据结构] 二叉树中序遍历(非递归)

#include <iostream>
#include <string>
#include <stack>

using namespace std;

class BiTreeNode
{
public :
    char data;
    BiTreeNode *LeftChild;
    BiTreeNode *RightChild;
    BiTreeNode():LeftChild(NULL), RightChild(NULL){}
    ~BiTreeNode(){}
};

class BiTree
{
private:
    BiTreeNode *Root;
    stack<BiTreeNode*> st;
    int pos;
    string strTree;
    BiTreeNode* CreateBiTree(); //先序创建二叉树
    void PreOrder(BiTreeNode *t);
    void InOrder(BiTreeNode *t);
    void PostOrder(BiTreeNode *t);
    void InOrder_Stack(BiTreeNode *t);
public:
    BiTree(){};
    ~BiTree(){};
    void CreateTree(string TreeArray);
    void PreOrder();
    void InOrder();
    void PostOrder();
    void InOrder_Stack();
};

void BiTree::InOrder_Stack()
{
    BiTreeNode *t;
    t = Root;
    InOrder_Stack(t);
}

void BiTree::InOrder_Stack(BiTreeNode *t)
{
    BiTreeNode *p;
    p=t;
    while(p || !st.empty())
    {
        if(p)
        {
            st.push(p);
            p = p->LeftChild;
        }
        else
        {
            p = st.top();
            cout<<p->data;
            st.pop();
            p = p->RightChild;
        }

    }

}

void BiTree::PostOrder()
{
    BiTreeNode *t;
    t = Root;
    PostOrder(t);
}

void BiTree::PostOrder(BiTreeNode *t)
{
    if(t)
    {
        PostOrder(t->LeftChild);
        PostOrder(t->RightChild);
        cout<<t->data;
    }
}


void BiTree::InOrder()
{
    BiTreeNode *t;
    t = Root;
    InOrder(t);
}

void BiTree::InOrder(BiTreeNode *t)
{
    if(t)
    {
        InOrder(t->LeftChild);
        cout<<t->data;
        InOrder(t->RightChild);
    }
}

void BiTree::PreOrder()
{
    BiTreeNode *t;
    t = Root;
    PreOrder(t);
}

void BiTree::PreOrder(BiTreeNode *t)
{
    if(t)
    {
        cout<<t->data;
        PreOrder(t->LeftChild);
        PreOrder(t->RightChild);
    }
}

void BiTree::CreateTree(string TreeArray)
{
    pos=0;
    strTree.assign(TreeArray);
    Root = CreateBiTree();
}

BiTreeNode* BiTree::CreateBiTree()
{
    BiTreeNode *T;
    char ch;
    ch = strTree[pos++];
    if(ch=='0' || ch==0)
        T=NULL;
    else
    {
        T = new BiTreeNode();
        T->data = ch;
        T->LeftChild = CreateBiTree();
        T->RightChild = CreateBiTree();
    }
    return T;
}

int main()
{
    BiTree test;
    string str;
    cin>>str;
    test.CreateTree(str);
    test.PreOrder(); cout<<endl;
    test.InOrder(); cout<<endl;
    test.PostOrder(); cout<<endl;
    test.InOrder_Stack(); cout<<endl;
}

  • 0
    点赞
  • 0
    评论
  • 1
    收藏
  • 一键三连
    一键三连
  • 扫一扫,分享海报

©️2021 CSDN 皮肤主题: 1024 设计师:白松林 返回首页
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值