C语言 | Leetcode C语言题解之第106题从中序与后序遍历序列构造二叉树

题目:

题解:

cpp 复制代码
int post_idx;

typedef struct {
    int key;
    int val;
    UT_hash_handle hh;
} hashTable;

hashTable* idx_map;

void insertHashTable(int x, int y) {
    hashTable* rec = malloc(sizeof(hashTable));
    rec->key = x;
    rec->val = y;
    HASH_ADD_INT(idx_map, key, rec);
}

int queryHashTable(int x) {
    hashTable* rec;
    HASH_FIND_INT(idx_map, &x, rec);
    return rec->val;
}

struct TreeNode* helper(int in_left, int in_right, int* inorder, int* postorder) {
    // 如果这里没有节点构造二叉树了,就结束
    if (in_left > in_right) {
        return NULL;
    }

    // 选择 post_idx 位置的元素作为当前子树根节点
    int root_val = postorder[post_idx];
    struct TreeNode* root = malloc(sizeof(struct TreeNode));
    root->val = root_val;

    // 根据 root 所在位置分成左右两棵子树
    int index = queryHashTable(root_val);

    // 下标减一
    post_idx--;
    // 构造右子树
    root->right = helper(index + 1, in_right, inorder, postorder);
    // 构造左子树
    root->left = helper(in_left, index - 1, inorder, postorder);
    return root;
}

struct TreeNode* buildTree(int* inorder, int inorderSize, int* postorder, int postorderSize) {
    // 从后序遍历的最后一个元素开始
    post_idx = postorderSize - 1;

    // 建立(元素,下标)键值对的哈希表
    idx_map = NULL;
    int idx = 0;
    for (int i = 0; i < inorderSize; i++) {
        insertHashTable(inorder[i], idx++);
    }

    return helper(0, inorderSize - 1, inorder, postorder);
}
相关推荐
卷卷的小趴菜学编程18 分钟前
linux第四讲----基础开发工具vim
linux·运维·服务器·c语言·开发语言
智者知已应修善业37 分钟前
2021-05-27 C++找出矩阵数组中值最大的元素和它在数组中的位置
c语言·c++·经验分享·算法·矩阵
快敲代码去37 分钟前
c语言实现三子棋小游戏(涉及二维数组、函数、循环、常量、动态取地址等知识点)
c语言·开发语言·后端·visual studio code
graceyun10 小时前
初阶数据结构(C语言实现)——3顺序表和链表(2)
c语言·数据结构·链表
charlie11451419110 小时前
深入讨论C语言的可能抽象:部分对设计模式的思考
c语言·学习·设计模式·软件工程
夏末秋也凉11 小时前
力扣-动态规划-62 不同路径
算法·leetcode·动态规划
pljnb12 小时前
【LeetCode 热题100】 240. 搜索二维矩阵 II的算法思路及python代码
算法·leetcode·矩阵
猫猫的小茶馆12 小时前
基于嵌入式linux的数据库:SQLite
linux·服务器·c语言·数据库·单片机·ubuntu·sqlite
juechen33312 小时前
如何更改vim命令创建代码文件时的默认模板
linux·c语言·编辑器·vim·vimplus
七七七七0712 小时前
浅谈C++/C命名冲突
c语言·c++