zoukankan      html  css  js  c++  java
  • 计蒜客 神奇的二叉树 ( 已知先序和中序遍历构建二叉树 )


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


    #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("
    ");
        image_postorder(root);
        printf("
    ");
        return 0;
    }
  • 相关阅读:
    HTTP、HTTP2
    1-1 用本地代码调试线上环境代码
    js判断触摸方向
    1-1 node 基础
    1-2 nodejs小节 文件读取
    c++ 递归斐波那契算法及时间复杂度
    十进制转换成二进制以 二进制转换成 8进制和16进制
    centos6.5 安装cmake 3.3.2
    回文字符串
    -Dmaven.multiModuleProjectDirectory system property is not set. Check $M2_HOME environment variable
  • 原文地址:https://www.cnblogs.com/WArobot/p/7118502.html
Copyright © 2011-2022 走看看