神奇的二叉树

在这里插入图片描述

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct Node
{
    int data;
    struct Node* lchild, * rchild;
}Node;

Node* init(int data)
{
    Node* node = (Node*)malloc(sizeof(Node));
    node->data = data;
    node->lchild = NULL;
    node->rchild = NULL;
    return node;
}
void preorder(Node* node)
{
    printf("%c ", node->data);
    if (node->lchild != NULL)
    {
        preorder(node->lchild);
    }
    if (node->rchild != NULL)
    {
        preorder(node->rchild);
    }
}
void inorder(Node* node)
{

    if (node->lchild != NULL)
    {
        inorder(node->lchild);
    }
    printf("%c ", node->data);
    if (node->rchild != NULL)
    {
        inorder(node->rchild);
    }
}
void pastorder(Node* node)
{
    if (node->lchild != NULL)
    {
        pastorder(node->lchild);
    }
    if (node->rchild != NULL)
    {
        pastorder(node->rchild);
    }
    printf("%c", node->data);
}
void mirrororder(Node* node)
{
    if (node->rchild != NULL)
    {
        mirrororder(node->rchild);
    }
    if (node->lchild != NULL)
    {
        mirrororder(node->lchild);
    }
    printf("%c", node->data);
}
Node* build(char* pre_str, char* in_str, int len)
{
    Node* p = init(pre_str[0]);
    int pos = strchr(in_str, pre_str[0]) - in_str;
    //由于strchr函数返回的是地址,所以需要在函数后面减去首地址in_str,这样才能得到pos
    if (pos > 0)//左子树不为空
    {
        p->lchild = build(pre_str + 1, in_str, pos);
         /*先序遍历中pre_str是第0位根节点,第一位开始是左子树的结点,用pre_str+1表从
        pre_str第一位以后的字符串,左子树的中序遍历是in_str里第0位开始的字符串
        pos中序遍历的长度,根结点前面字符总数,有pos个*/
    }
    if (len - pos - 1 > 0)
    {
        p->rchild = build(pre_str + pos + 1, in_str + pos + 1, len - pos - 1);
        /*先序遍历pre_str从pos+1开始到末位都是右子树结点,可以用ptr_str+pos+1来表示
        表示取pre_str第pos+1位到末位的字符串,中序遍历根节点后的结点都是右子树的结点,用
        pre_str+pos+1表示取in_str第pos+1位到末位的字符串,右子树中遍历长度为len-pos-1
        */
    }
    return p;
}

void clear(Node* node)
{
    if (node->lchild != NULL)
    {
        clear(node->lchild);
    }
    if (node->rchild != NULL)
    {
        clear(node->rchild);
    }
    free(node);
}
int main()
{
    char pre_str[51];
    scanf("%s", pre_str);
    char in_str[51];
    scanf("%s", in_str);
    Node* root = build(pre_str, in_str, strlen(pre_str));
    pastorder(root);
    printf("\n");
    mirrororder(root);
    printf("\n");
    clear(root);
    return 0;
}
  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值