C语言N叉树非递归(前中后遍历法)

#include <stdio.h>
#include <stdlib.h>

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)
            {
                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;
}

猜你喜欢

转载自blog.csdn.net/qq_40663787/article/details/83342603