输出以二叉树表示的算术表达式(严6.51)

本文介绍了一种将先序遍历的二叉树转换为带括号的中序算术表达式的算法实现。通过递归创建二叉树并进行中序遍历输出,实现了从输入的先序字符串到正确算术表达式的转换。

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

Description

编写程序,输出以二叉树表示的算术表达式,若该表达式中含有括号,则在输出时应添上。

Input

按先序输入一行字符,其中#表示取消建立子树结点,即所有叶子节点均为#。

Output

输出该二叉树所表示的算术表达式(若表达式中含有括号,则在输出时应添上)。

  • Sample Input 
    *+a(###b#)##c##
  • Sample Output
    (a+b)*c
#include <stdlib.h>
#include <stdio.h>
#include <malloc.h>

typedef struct BinTreeNode
{
    char data;
    struct BinTreeNode *lchild;
    struct BinTreeNode *rchild;
}BinTree, *PBinTree;

PBinTree CreateBinTree()
{
    PBinTree root = (PBinTree)malloc(sizeof(BinTree));
    char c = getchar();
    if(c == '#')
        return NULL;
    else
    {
        root->data = c;
        root->lchild = CreateBinTree();
        root->rchild = CreateBinTree();

    }
    return root;
}

void PrintBinTree (struct BinTreeNode *p)
{
    if(p->lchild)
    {
        PrintBinTree(p->lchild);
    }
    printf("%c",p->data);
    if(p->rchild)
    {
        PrintBinTree(p->rchild);
    }
}
int main()
{
    PBinTree T;
    T = CreateBinTree();
    PrintBinTree(T);
    return 0;
}

实际上就是一个先序输出变成中序

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值