输出中序遍历下最后一个结点

#include<stdio.h>

#include<stdlib.h>

 

typedef char datatype; //树结构体的定义

typedef struct node {

    datatype data;

    struct node *lchild, *rchild;

} bintree;

bintree *root;

 

typedef struct stack //栈的结构定义

{

    bintree *data[100];

    int tag[100];   //为栈中的每个元素设计标记,用于后序遍历

    int top; //栈顶指针

} seqstack;

 

void push(seqstack *s, bintree *t) //进栈

{

    s->data[s->top] = t;

    s->top++;

}

 

bintree *pop(seqstack *s//出栈

{

    if (s->top != 0)

    {

         s->top--;

         return (s->data[s->top]);

    }

    else

         return NULL;

}

 

bintree *createbintree() //按照前序遍历顺序建立一颗给定的二叉树(递归)

{

    char ch;

    bintree *t;

    if ((ch = getchar()) == '#')

         t = NULL;

    else {

         t = (bintree*)malloc(sizeof(bintree));

         t->data = ch;

         t->lchild = createbintree();

         t->rchild = createbintree();

    }

    return t;

}

 

void inorder1(bintree *t) //非递归实现二叉树的中序遍历

{

    seqstack s;

    s.top = 0;

    while ((t) || (s.top != 0))

    {

         if (t)

         {

             push(&s, t);

             t = t->lchild;

         }

         else

         {

             t = pop(&s);

             printf("%c", t->data);

             t = t->rchild;

         }

    }

}

 

 

bintree *last(bintree *t) //计算中序遍历的最后一个结点

{

    if (t->rchild)

    {

         while (t->rchild)

         {

             t = t->rchild;

         }

    }

    return t;

}

 

int main()

{

    bintree *tree;

    bintree *l;

    printf("根据前序遍历输入一棵二叉树:");

    tree = createbintree();

    printf("\n");

    printf("中序遍历输出二叉树:");

    inorder1(tree);

    printf("\n");

    l = last(tree);

    printf("中序遍历下最后一个结点:");

    printf("%c",l->data);

    printf("\n");

    return 0;

}

猜你喜欢

转载自blog.csdn.net/weixin_43703670/article/details/84100721