#include
#include
using namespace std;
typedef struct BiTNode
{
int data;
BiTNode *lchild,*rchild;
}BiTNode;
BiTNode* goLeft(BiTNode* T,stack &s)
{
if(T == NULL)
{
return NULL;
}
//如果有左子树 入栈 返回起点
while(T->lchild)
{
s.push(T);
T = T->lchild;
}
return T;
}
void inOrder01(BiTNode* T)
{
BiTNode* t = NULL;
stack s;
if(T == NULL)
{
return;
}
//步骤1 找到左起点
t = goLeft(T,s);
while(t)
{
printf("%d ",t->data);
//如果有右子树 重复步骤1
if(t->rchild)
{
t = goLeft(t->rchild,s);
}
else if(!s.empty())
{
t = s.top();
s.pop();
}
else
{
t = NULL;
}
}
}
void preOrder01(BiTNode* T)
{
stack s;
BiTNode* t = NULL;
if(T == NULL)
{
return;
}
t = T;
while(t)
{
printf("%d ",t->data);
if(t->lchild)
{
if(t->rchild)
{
s.push(t->rchild);
}
t = t->lchild;
}
else if(t->rchild)
{
t = t->rchild;
}
else if(!s.empty())
{
t = s.top();
s.pop();
}
else
{
t = NULL;
}
}
}
void goLeft1(BiTNode* T,stack &s)
{
BiTNode* t = NULL;
if(T == NULL)
{
return;
}
while(T)
{
s.push(T);
t = T;
T = T->lchild;
if(T == NULL)
{
T = t->rchild;
}
}
}
void postOrder01(BiTNode* T)
{
stack s;
BiTNode* t = NULL;
BiTNode* tmp = NULL;
if(T == NULL)
{
return;
}
goLeft1(T,s);
if(!s.empty())
{
t = s.top();
}
while(t)
{
if(!t->rchild || t->rchild == tmp)
{
printf("%d ", t->data);
tmp = t;
s.pop();
//t = s.top();
if(!s.empty())
{
t = s.top();
}
else
{
t = NULL;
}
}
else
{
goLeft1(t->rchild,s);
if(!s.empty())
{
t = s.top();
}
else
{
t = NULL;
}
}
}
}
void main()
{
BiTNode t1,t2,t3,t4,t5; //定义树的节点
memset(&t1,0,sizeof(BiTNode));
memset(&t2,0,sizeof(BiTNode));
memset(&t3,0,sizeof(BiTNode));
memset(&t4,0,sizeof(BiTNode));
memset(&t5,0,sizeof(BiTNode));
t1.data = 1;
t2.data = 2;
t3.data = 3;
t4.data = 4;
t5.data = 5;
//建立节点之间的关系
t1.lchild = &t2;
t1.rchild = &t3;
t2.lchild = &t4;
t3.lchild = &t5;
printf("非递归前序遍历\n");
preOrder01(&t1);
printf("\n");
printf("非递归中序遍历:\n");
inOrder01(&t1);
printf("\n");
printf("非递归后序遍历:\n");
postOrder01(&t1);
printf("\n");
{
BiTNode t1,t2,t3,t4,t5,t6; //定义树的节点
memset(&t1,0,sizeof(BiTNode));
memset(&t2,0,sizeof(BiTNode));
memset(&t3,0,sizeof(BiTNode));
memset(&t4,0,sizeof(BiTNode));
memset(&t5,0,sizeof(BiTNode));
memset(&t6,0,sizeof(BiTNode));
t1.data = 1;
t2.data = 2;
t3.data = 3;
t4.data = 4;
t5.data = 5;
t6.data = 6;
t1.lchild = &t2;
t2.lchild = &t3;
t2.rchild = &t4;
t1.rchild = &t5;
t5.rchild = &t6;
printf("非递归前序遍历\n");
preOrder01(&t1);
printf("\n");
printf("非递归中序遍历:\n");
inOrder01(&t1);
printf("\n");
printf("非递归后序遍历:\n");
postOrder01(&t1);
printf("\n");
}
printf("hello...\n");
system("pause");
return;
}