c语⾔N叉树,C语⾔N叉树⾮递归(前中后遍历法)#include typedef struct kk
{
char ch;
int flag;
struct kk *left;
struct kk *right;
}btree;
typedef struct stack
{
btree *btree[20];
int top;
}seqStack;
void push(seqStack *s,btree *t)
{
s->btree[s->top] = t;
s->top++;
t->flag = 0;
}
void pop(seqStack *s)
{
if (s->top != 0)
s->top--;
else
return;
}
btree *top(seqStack *s)
{
return s->btree[s->top-1];
}
void initStack(seqStack *s)
{
s->top = 0;
}
int isEmpty(seqStack *s) {
if (s->top == 0)
return 1;
else
return 0;
}
btree *CreateTree()
{
btree *t;
char ch;
ch = getchar();
if (ch == '#')
return NULL;
else
{
t = malloc(sizeof(btree)); t->ch = ch;
t->left = CreateTree();
t->right = CreateTree(); }
return t;
}
void Pre_order1(btree *t) {
seqStack s;
initStack(&s);
push(&s,t);
while (!isEmpty(&s))
{
t = top(&s);
if (t == NULL)
pop(&s);
else
if (t->flag == 0)
{
printf("%c",t->ch);
if (t->left != NULL)
push(&s,t->left);
t->flag = 1;
}
else if (t->flag == 1)
{
if (t->right != NULL)
push(&s,t->right);
pop(&s);
}
}
}
}
void Post_order1(btree *t) {
seqStack s;
initStack(&s);
push(&s,t);
while (!isEmpty(&s))
{
t = top(&s);
if (t == NULL)
pop(&s);
else
{
if (t->flag == 0)
{
递归函数c语言规则if (t->left != NULL)
push(&s,t->left);
t->flag = 1;
else if (t->flag == 1) {
if (t->right != NULL) push(&s,t->right);
t->flag = 2;
}
else if (t->flag == 2) {
printf("%c",t->ch); pop(&s);
}
}
}
}
int main()
{
btree *t;
t = CreateTree(); Pre_order1(t); putchar('\n');
Post_order1(t); return 0;
}
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论