4 二叉树的输出——凹入表示法 二叉树输出

文章介绍了如何根据先序遍历和中序遍历的字符串,利用树的凹入表示法在C++中构建二叉树,并实现层次遍历的输出。给出输入的先序和中序遍历序列,输出对应二叉树的层次结构字符表示。
摘要由CSDN通过智能技术生成

Background

Special for beginners, ^_^

Description

树的凹入表示法主要用于树的屏幕或打印输出,其表示的基本思想是兄弟间等长,一个结点的长度要不小于其子结点的长度。二叉树也可以这样表示,假设叶结点的长度为1,一个非叶结点的长度等于它的左右子树的长度之和。

一棵二叉树的一个结点用一个字母表示(无重复),输出时从根结点开始:

每行输出若干个结点字符(相同字符的个数等于该结点长度),

如果该结点有左子树就递归输出左子树;

如果该结点有右子树就递归输出右子树。

假定一棵二叉树一个结点用一个字符描述,现在给出先序和中序遍历的字符串,用树的凹入表示法输出该二叉树。

Format

Input

输入共两行,每行是由字母组成的字符串(一行的每个字符都是唯一的),分别表示二叉树的先序遍历和中序遍历的序列。字符串长度小于50。

Output

输出的行数等于该树的结点数,每行的字母相同。

Samples

样例输入

ABCDEFG
CBDAFEG

样例输出

AAAA
BB
C
D
EE
F
G

#include <iostream>
#include <cstring>
using namespace std;

#define MaxSize 100

struct TreeNode
{
    char val;
    struct TreeNode *left;
    struct TreeNode *right;
};

struct TreeNode *createNode(char val)
{
    struct TreeNode *newNode = (struct TreeNode *)malloc(sizeof(struct TreeNode));
    newNode->val = val;
    newNode->left = NULL;
    newNode->right = NULL;
    return newNode;
}

int search(char arr[], int start, int end, char value)
{
    for (int i = start; i <= end; i++)
    {
        if (arr[i] == value)
            return i;
    }
    return -1;
}

struct TreeNode *buildTree(char preorder[], char inorder[], int inStart, int inEnd, int *preIndex)
{
    if (inStart > inEnd)
        return NULL;

    struct TreeNode *newNode = createNode(preorder[*preIndex]);
    (*preIndex)++;

    if (inStart == inEnd)
        return newNode;

    int inIndex = search(inorder, inStart, inEnd, newNode->val);

    newNode->left = buildTree(preorder, inorder, inStart, inIndex - 1, preIndex);
    newNode->right = buildTree(preorder, inorder, inIndex + 1, inEnd, preIndex);

    return newNode;
}

int FindLeaves(struct TreeNode *root)
{
    if (root == NULL)
    {
        return 0;
    }
    if (root->left == NULL && root->right == NULL)
    {
        return 1;
    }
    int count = 0;
    count += FindLeaves(root->left);
    count += FindLeaves(root->right);
    return count;
}

void PreOrder(struct TreeNode *root)
{
    if (root != NULL)
    {
        for (int i = 0; i < FindLeaves(root); i++)
        {
            cout << root->val;
        }
        cout << endl;
        PreOrder(root->left);
        PreOrder(root->right);
    }
}

int main()
{
    int n;

    char inorder[MaxSize];
    char levelorder[MaxSize];

    cin.getline(inorder, MaxSize);
    cin.getline(levelorder, MaxSize);

    n = strlen(inorder);

    int preIndex = 0;
    struct TreeNode *root = buildTree(inorder, levelorder, 0, n - 1, &preIndex);

    PreOrder(root);

    return 0;
}

  • 16
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值