计蒜客 神奇的二叉树 ( 已知先序和中序遍历构建二叉树 )


思路: 题目要求输出在镜子里看到的二叉树 , 观察后可以发现 , 镜像的二叉树后序遍历实际上是先遍历右子树再遍历左子树再遍历根 , 所以只需要改一下后序遍历顺序即可.


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

#define MAX_N 50
typedef struct Node {
    char data;
    struct Node *lchild , *rchild;
}Node;

Node* init(char data) {
    Node *node = (Node*)malloc(sizeof(Node));
    node->lchild = NULL;    node->rchild = NULL;
    node->data = data;
    return node;
}
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;
    if (pos > 0) {
        p->lchild = build(pre_str + 1 , in_str , pos);
    }
    if (pos < len - 1) {
        p->rchild = build(pre_str + pos + 1 , in_str + pos + 1 , len - pos - 1);
    }
    return p;
}
void postorder(Node *node) {
    if (node->lchild != NULL) {
        postorder(node->lchild);
    }
    if (node->rchild != NULL) {
        postorder(node->rchild);
    }
    printf("%c",node->data);
}
void image_postorder(Node *node) {
    if (node->rchild != NULL) {
        image_postorder(node->rchild);
    }
    if (node->lchild != NULL) {
        image_postorder(node->lchild);
    }
    printf("%c",node->data);
}
int main() {
    char pre_str[MAX_N + 10] , in_str[MAX_N + 10];    
    scanf("%s %s",pre_str , in_str);
    Node *root = build(pre_str , in_str , strlen(pre_str));
    postorder(root);
    printf("\n");
    image_postorder(root);
    printf("\n");
    return 0;
}

转载于:https://www.cnblogs.com/WArobot/p/7118502.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值