试编写一个函数,返回一颗给定二叉树在中序遍历下的最后一个节点(分别用递归和非递归实现)

试编写一个函数,返回一颗给定二叉树在中序遍历下的最后一个节点(分别用递归和非递归实现)


#include 
   
   
    
    
#include 
    
    
     
     
#define MAXSIZE 50

typedef char datatype;
typedef struct node
{
    datatype data;
    struct node *lchild,*rchild;
} bintnode,*bintree;
datatype a;//用来记录中序遍历最后一个节点
//用来存放非递归的根节点
typedef struct
{
    bintree a[MAXSIZE];
    int top;
} stack;

bintree inputbint()
{
    datatype in;
    bintree t;
    if((in=getchar())=='#')
        t=NULL;
    else
    {
        t=(bintnode *)malloc(sizeof(bintnode));
        t->data=in;
        t->lchild=inputbint();
        t->rchild=inputbint();
    }
    return t;
}

//前序遍历输出当前二叉树
void printbint(bintree root)
{
    if(root==NULL)return;
    else
    {
        printf("%c",root->data);
        printbint(root->lchild);
        printbint(root->rchild);
    }
}

void findlast(bintree root)
{
    if(root)
    {
        findlast(root->lchild);
        a=root->data;
        findlast(root->rchild);
    }
}

datatype findlast2(bintree root)
{
    datatype b;
    stack s;
    s.top=0;
    do
    {
        if(root!=NULL)
        {
            s.a[s.top]=root;
            s.top++;
            root=root->lchild;
        }
        else
        {
            s.top--;
            root=s.a[s.top];
            if(root->rchild==NULL)
            {
                b=root->data;
            }
            root=root->rchild;
        }
    }
    while(s.top!=0||root!=NULL);
    return b;
}

int main()
{
    bintree root;
    datatype b;//为避免与递归混淆,为外声明b供非递归使用
    printf("请输入二叉树,子节点为空请输#:\n");
    root=inputbint();
    printf("前序遍历输出二叉树为:");
    printbint(root);
    printf("\n");
    findlast(root);//递归方式查找最后一个节点
    printf("递归实现输出中序遍历最后一个节点为:");
    printf("%c\n",a);
    b=findlast2(root);
    printf("非递归实现输出中序遍历最后一个节点为:");
    printf("%c",b);
    return 0;
}

    
    
   
   

  • 2
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值