#include<stdio.h>
#include<stdlib.h>
#define STACKINITSIZE 100
#define STACKINCREASESIZE 20
typedef char ElemType;
//树结构
typedef struct tree
{
ElemType data;
struct tree * lchild;
struct tree * rchild;
}TreeNode,*Tree;
//栈结构
typedef struct stack
{
Tree * base;//栈底
Tree * top;//栈顶
int stacksize;
}Sqstack;
//初始化栈
void InitStack( Sqstack &s )
{
s.base = (Tree *)malloc(STACKINITSIZE*sizeof(Tree));
if ( !s.base )
{
printf("InitStack内存分配出错\n");
}
s.top = s.base;
s.stacksize = STACKINITSIZE;
}
//元素入栈
void Push( Sqstack &s, Tree e )
{
*s.top++ = e;
}
//出栈顶元素
void Pop( Sqstack &s, Tree &e )
{
if ( s.top == s.base )
{
printf("栈为空\n");
return ;
}
e = *(--s.top);
}
//判断栈是否为空,为空返回1,否则返回0
int StackEmpty( Sqstack s )
{
if ( s.top == s.base )
return 1;
return 0;
}
//创建树,以先序序列建立树
void CreateTree(Tree &t)
{
char ch;
scanf("%c",&ch);
if ( ch == '#' )//#表示空
t = NULL;
else
{
t = (Tree)malloc(sizeof(TreeNode));
t->data = ch;
CreateTree(t->lchild);
CreateTree(t->rchild);
}
}
//递归先序遍历
void PreOrder(Tree t)
{
if ( t )
{
printf("%c",t->data);
PreOrder(t->lchild);
PreOrder(t->rchild);
}
}
//非递归中序遍历
void InOrder1(Tree t)
{
Tree p = t;
Sqstack s;
InitStack(s);
while ( p || !StackEmpty(s) )
{
if ( p )
{
Push(s,p);
p = p->lchild;
}
else
{
Pop(s,p);
printf("%c",p->data);
p = p->rchild;
}
}
}
int main()
{
Tree T;
printf("\n按先序序列输入结点序列,'#'代表空:");
CreateTree(T);
printf("\n递归先序遍历的结果: ");
PreOrder(T);
printf("\n非递归中序遍历的结果:");
InOrder1(T);
return 0;
}
二叉树递归非递归
最新推荐文章于 2021-06-04 17:15:06 发布