NOJ-输出以二叉树表示的算数表达式-西工大数据结构

    我发现这几道二叉树的题是真的像,方法都差不多,就稍微修改一下函数就能通过,真的是无力吐槽。。。。。。

    下面是题目:

    明明是一个前序变中序,还整得这么玄乎。。。。。。


    分析一下题目,它是将一个先序的一串数据整到二叉树里,数据若是‘#’就为NULL。最后按表达式输出。

    输入我决定采用递归的方法,每次读入一个数据,若是字母或符号就说明他是一个根节点,若是‘#’说明上个节点没有当前分支,返回NULL即可。由此,+a(b*###)##  (即a+(b*c))可转换成如下二叉树:


     输出我也选择递归的方法,分析一下,要想实现表达式必须采用中序输出,先左支后该节点再右支,如下图:


    以下是我的实现:

#include <stdio.h>
#include <stdlib.h>

struct binaryTree
{
    char data;
    struct binaryTree *left;
    struct binaryTree *right;
};

void run ();
struct binaryTree *createNewBinaryTree ();
void printBinaryTree (struct binaryTree *head);

int main()
{
    run ();
    return 0;
}

struct binaryTree *createNewBinaryTree ()
{
    char s;
    struct binaryTree *cur;
    s=getchar ();
    if (s=='#')
    {
        return NULL;
    }
    else
    {
        cur=(struct binaryTree*)malloc(sizeof(struct binaryTree));
        cur->data=s;
        cur->left=createNewBinaryTree ();
        cur->right=createNewBinaryTree ();
        return cur;
    }
}

void run ()
{
    struct binaryTree *head;
    head=createNewBinaryTree ();
    printBinaryTree (head);
}

void printBinaryTree (struct binaryTree *head)
{
    if (head->left)
    {
        printBinaryTree (head->left);
    }
    printf ("%c",head->data);
    if (head->right)
    {
        printBinaryTree (head->right);
    }
}

下面是各函数的注释:

struct binaryTree *createNewBinaryTree ()
{
    char s;
    struct binaryTree *cur;
    s=getchar ();//读入数据
    if (s=='#')//若为‘#’
    {
        return NULL;
    }
    else//若为字母或符号
    {
        cur=(struct binaryTree*)malloc(sizeof(struct binaryTree));//创建节点并赋值
        cur->data=s;
        cur->left=createNewBinaryTree ();//左支递归
        cur->right=createNewBinaryTree ();//右支递归
        return cur;//返回当前节点便于递归
    }
}
void printBinaryTree (struct binaryTree *head)
{
    if (head->left)//若左支存在
    {
        printBinaryTree (head->left);//递归输出左支
    }
    printf ("%c",head->data);//输出当前节点
    if (head->right)//若右支存在
    {
        printBinaryTree (head->right);//递归输出右支
    }
}
    以上就是我的实现,希望给大家带来帮助。

猜你喜欢

转载自blog.csdn.net/qq_30180107/article/details/79888474