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

本文详细介绍了如何使用C语言创建二叉树,并通过递归和非递归方式实现二叉树的中序遍历。此外,还提供了一个计算中序遍历最后一个节点的算法,帮助读者深入理解二叉树的结构和遍历过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#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;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值