二叉树及其应用--二叉树的应用

这篇博客探讨了二叉树的相关应用,包括通过前序遍历构造二叉树并输出广义表、竖向及横向树状表示,以及根据前序和中序遍历确定二叉树并输出后序遍历,最后介绍了如何从后缀表达式构建表达式树并输出其前序和中序遍历。
摘要由CSDN通过智能技术生成

二叉树带节点数输出
给出二叉树的先序遍历输出(空结点用’.’)表示,请构造二叉树,并输出二叉树的广义表表示,此广义表中每个结点均带有一个整数,这个整数表示对应的子树上结点总数。

输入说明:
一行仅由‘.’与大小写字符构成的字符串,该字符串表示二叉树的前序遍历输出,其中’.’表示空结点,字符串长度不超过100。
输出说明:
在单独一行中二叉树的广义表表示,此广义表中每个结点均带有一个整数,这个整数表示对应的子树上结点总数。具体格式参考输出样例。
输入样列:
ABD…C..
输出样列:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <queue>
#include <cctype>
using namespace std;
#define N 100
typedef char Element;
struct Node
{
    Element data;
    int num;
    struct Node *lchild;
    struct Node *rchild;
};
typedef struct Node BTNode;
typedef struct Node * BTree;
BTree Create_BTree();
BTree NewNode(Element x);
void PrintBTreeNum(BTree root);
void Pre_Order(BTree root);
int GetNum(BTree root);
int main()
{
    BTree root;
    root=Create_BTree();
    Pre_Order(root);
    PrintBTreeNum(root);
    printf("\n");
    return 0;
}
BTree NewNode(Element x)
{
    BTree p=(BTree)malloc(sizeof(BTNode));
    p‐>data=x;
    p‐>lchild=NULL;
    p‐>rchild=NULL;
    return p;
}
BTree Create_BTree()
{
    BTree root;
    char c;
    c=getchar();
    if(c=='.')
        return NULL;
    root=NewNode(c);
    root‐>lchild=Create_BTree();
    root‐>rchild=Create_BTree();
    return root;
}
void Pre_Order(BTree root)
{
    if(root!=NULL)
    {
        root‐>num=GetNum(root);
        Pre_Order(root‐>lchild);
        Pre_Order(root‐>rchild);
    }
}
int GetNum(BTree root)
{
    int num;
    if(root==NULL)
        return 0;
    num=1;
    if(root‐>lchild!=NULL)
        num+=GetNum(root‐>lchild);
    if(root‐>rchild!=NULL)
        num+=GetNum(root‐>rchild);
    return num;
}
void PrintBTreeNum(BTree root)
{
    if(root==NULL);
    printf("%c[%d]",root‐>data,root‐>num);
    if(root‐>lchild==NULL&&root‐>rchild==NULL);
    printf("(");
    if(root‐>lchild!=NULL)
        PrintBTreeNum(root‐>lchild);
    printf(",");
    if(root‐>rchild!=NULL)
        PrintBTreeNum(root‐>rchild);
    printf(")");
}

二叉树树状输出I
给出二叉树的先序遍历输出(空结点用’.’)表示,请构造二叉树,并按树状输出该二叉树(竖向)。

输入说明:
一行仅由‘.’与大小写字符构成的字符串,该字符串表示二叉树的前序遍历输出,其中’.’表示空结点,字符串长度不超过100。
输出说明:
输出有若干行,为二叉树的树状输出(竖向),具体格式参考输出样例,为明显起见࿰

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值