#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>
#include <queue>
#include <stack>
#include <iostream>
using namespace std;
typedef struct BiTNode{
char data;
BiTNode *lchild, *rchild;
}BiTNode,*BiTree;
BiTree T;
void CreateBiTree(BiTree &T)
{
char ch;
scanf("%c",&ch);
if(ch=='@')
{
T=NULL;
return;
}
else
{
T=(BiTree)malloc(sizeof(BiTNode));
T->data=ch;
CreateBiTree(T->lchild);
CreateBiTree(T->rchild);
}
}
void midTraverse(BiTree T)
{
stack<BiTree> S;
if(!T)
{
printf("空树!\n");
return;
}
while(T || !S.empty())
{
while(T)
{
S.push(T);
T=T->lchild;
}
T=S.top();
S.pop();
printf("%c",T->data);
T=T->rchild;
}
}
void PreTraverse(BiTree T)
{
stack<BiTree> S;
if(!T)
{
printf("空树!\n");
return;
}
while(T || !S.empty())
{
while(T)
{
S.push(T);
printf("%c",T->data);
T=T->lchild;
}
T=S.top();
S.pop();
T=T->rchild;
}
}
void behindTraverse(BiTree T)
{
stack<BiTree>S1;
stack<BiTree>S2;
BiTree cur;
S1.push(T);
if(!T)
{
printf("空树!\n");
return;
}
while(!S1.empty())
{
cur=S1.top();
S1.pop();
S2.push(cur);
if(cur->lchild)
S1.push(cur->lchild);
if(cur->rchild)
S1.push(cur->rchild);
}
while(!S2.empty())
{
cout<<S2.top()->data;
S2.pop();
}
}
int main()
{
CreateBiTree(T);
PreTraverse(T);
printf("\n");
midTraverse(T);
printf("\n");
behindTraverse(T);
printf("\n");
return 0;
}
二叉树的遍历 非递归操作
最新推荐文章于 2023-11-18 21:31:44 发布