# [数据结构] 二叉树中序遍历（非递归）

#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
收藏
• 一键三连
• 扫一扫，分享海报

11-11 2万+
11-16 480

06-07 551
01-10 2万+
01-04 1万+
05-15 498
01-14 781
04-02 557
04-20 2107
02-07 2024
07-06 11万+
01-04 1万+
11-05 1421
11-21 590
10-19 206
12-21 842