#include <cstdio>
#include <cstring>
#include <algorithm>
#include <iostream>
#include <malloc.h>
#include <stack>
using namespace std;
typedef struct BiTNode
{
char data;
struct BiTNode *L,*R;
}BiTNode,*BiTree;
int CreateBiTree(BiTree &T)
{
char ch;
scanf("%c",&ch);
if(ch==' ')T=NULL;
else
{
if(!(T=(BiTNode *)malloc(sizeof(BiTNode))))exit(-2);
T->data=ch;
CreateBiTree(T->L);
CreateBiTree(T->R);
}
return 0;
} //CreateBiTree
int Visit(char e)
{
printf("%c ",e);
return 0;
}
int PreOrderTraverse(BiTree T)
{
if(T)
{
Visit(T->data);
PreOrderTraverse(T->L);
PreOrderTraverse(T->R);
}
}
int INorderTraverse(BiTree T)//非递归中序遍历;
{
stack<BiTree> s;
BiTNode *p=T;
while(p||!s.empty())
{
if(p)
{
s.push(p);
p=p->L;
}
else
{
p=s.top();
s.pop();
Visit(p->data);
p=p->R;
}
}
return 0;
}
int InOrderTraverse(BiTree T)
{
if(T)
{
InOrderTraverse(T->L);
Visit(T->data);
InOrderTraverse(T->R);
}
}
int PostOrderTraverse(BiTree T)//后序遍历
{
if(T)
{
PostOrderTraverse(T->L);
PostOrderTraverse(T->R);
Visit(T->data);
}
}
int main()
{
BiTree T;
CreateBiTree(T);
printf("树的先序遍历结果:\n");
PreOrderTraverse(T);
printf("\n");
printf("树的中序遍历结果:\n");
InOrderTraverse(T);
printf("\n");
printf("树的中序非递归遍历结果:\n");
INorderTraverse(T);
printf("\n");
printf("树的后序遍历结果:\n");
PostOrderTraverse(T);
printf("\n");
}
二叉树
最新推荐文章于 2022-03-12 20:36:06 发布