📄 先序遍历二叉树非递归.c
字号:
#include<stdlib.h>
#include<stdio.h>
#define M0 100 //定义节点最大个数
#define M2 20 //定义栈的容量
#define LEN sizeof (BinNode) //定义节点空间
typedef struct BinNode //定义节点类型
{
char data;
struct BinNode *lch,*rch;
} BinNode,*Bintree;
struct chtp
{
int len;
char ch[M0];
};
struct BinNode *bt,*m,*stack[M2];
struct chtp s;
int top=0,i=0;
void crt_pre(Bintree *t) //递归建立二叉树
{
char c;
c=s.ch[i];
i=i+1;
if (c=='.')
*t=NULL;
else
{
*t=(BinNode *)malloc(LEN);
(*t)->data=c;
crt_pre(&(*t)->lch);
crt_pre(&(*t)->rch);
};
}
void preorder (BinNode *t) //非递归先序遍历二叉树子函数
{
top=0;
while(t!=NULL||top!=0)
{
while(t!=NULL)
{
printf("%c",(*t).data);
stack[++top]=t;
t=t->lch;
}
if(top!=0)
{
t=stack[top--]->rch;
}
}
}
void main()
{
char /*c[]={'a','b','d','.','.','.','c','e','.','.','f','.','.','!'};*/
c[]={'a','b','c','.','.','d','e','.','g','.','.','f','.','.','.','!'};
int i=0;
for(i=0,s.len=0;c[i]!='!';i++,s.len++)
s.ch[i]=c[i];
crt_pre(&bt);
preorder(bt);
printf("\n");
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -