0
点赞
收藏
分享

微信扫一扫

二叉树的先、中、后序遍历(非递归)

君心浅语 2022-04-02 阅读 101
#include<stdio.h>
#include<stdlib.h>
#define max 100
typedef struct node{
    int data;
    struct node *lchild;
    struct node *rchild;
}*btree,tree;
typedef struct list{
    btree data[max];
    int top;
}*node,Node;
node Init(){
    node n=(node)malloc(sizeof (Node));
    if(n)
        n->top=-1;
    return n;
}
void TreeInit(btree *t,char *str,int *x){
    char c;
    c=*(str+*x);
    *x=*x+1;
    if(c!='#')
    {
        *t=(btree)malloc(sizeof (tree));
        (*t)->data=c;
        TreeInit(&((*t)->lchild),str,x);
        TreeInit(&((*t)->rchild),str,x);
    }else {
        *t=NULL;
    }
}
//判断链是否为空
int Empty(node n){
    if(n->top==-1)
        return 1;
    else {
        return 0;
    }
}
//入栈
void push(node s,btree t)
{
    if(s->top==max-1)
        printf("栈满");
    else {
        s->top++;
        s->data[s->top]=t;
    }
}
//出栈
void pop(node s,btree *t)
{
    if(Empty(s))
        printf("栈空");
    *t=s->data[s->top];
    s->top--;
}
//非递归先序遍历
void xianxu(btree t){
    node s;
    btree p=t;
    s=Init();
    while (p||!Empty(s)) {
        if(p){
            printf("-->%c",p->data);
            push(s,p);
            p=p->lchild;

        }else {
            pop(s,&p);
            p=p->rchild;
        }
    }
}
//非递归中序遍历
void zhongxu(btree t)
{
    node s=Init();
    btree p=t;
    while (p||!Empty(s)) {
        if(p){
            push(s,p);
            p=p->lchild;
        }else {
            pop(s,&p);
            printf("-->%c",p->data);
            p=p->rchild;
        }
    }
}
//非递归后续遍历
void houxu(btree t){
    node s1,s2;
    btree p=t;
    s1=Init();
    s2=Init();
    while (p||!Empty(s2)) {
        if(p)
        {
            push(s1,p);
            push(s2,p);
            p=p->rchild;
        }else {
            pop(s2,&p);
            p=p->lchild;
        }
    }
    while (!Empty(s1)) {
        pop(s1,&p);
        printf("-->%c",p->data);
    }
}
int main()
{
    int x=0;
    btree t;
    TreeInit(&t,"ABD#G###CE##FH###",&x);
    xianxu(t);
    printf("\n");
    zhongxu(t);
    printf("\n");
    houxu(t);
    return 0;
}
举报

相关推荐

0 条评论