建立二叉树的二叉链表

本文介绍了一种根据给定的前序序列和中序序列构建二叉树的方法,并实现了后序遍历输出。通过递归算法创建二叉链表,展示了二叉树的基本操作。

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

已知一棵二叉树的前序序列和中序序列分别存于两个一维数组中,试编写算法建立该二叉树的二叉链表。

分两行分别输入一棵二叉树的前序序列和中序序列。

输出该二叉树的后序序列。

ABDFGCEH

BFDGACEH

FGDBHECA

#include <iostream>
#include <cstring>
#include <stdlib.h>
using namespace std;

typedef struct TreeNode
{
    struct TreeNode* lchild;
    struct TreeNode* rchild;
    char elem;
}TreeNode;

TreeNode* BinaryTree(char *preorder, char *inorder, int len)
{
    if(len <= 0)
        return NULL;
    TreeNode *root = (TreeNode*)malloc(sizeof(TreeNode));
    root->elem = preorder[0];
    int rootindex = -1;
    for(int i = 0; i < len; i ++)
    {
        if(inorder[i] == preorder[0])
        {
            rootindex = i;
            break;
        }
    }
    //cout << root->elem << endl;
    root->lchild = BinaryTree(preorder+1,inorder, rootindex);
    root->rchild = BinaryTree(preorder+rootindex+1,inorder+rootindex+1,len-rootindex-1);
    return root;
}

void Traversal(TreeNode *root)
{
    if(root != NULL)
    {
        Traversal(root->lchild);
        Traversal(root->rchild);
        cout << root->elem ;
    }
}
int main()
{
    char inorder[100];
    char preorder[100];
    cin >> preorder;
    cin >> inorder;
    int len = strlen(preorder);

    TreeNode * root = BinaryTree(preorder, inorder, len);
    Traversal(root);

    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值