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);
}
相关推荐
pumpkin845141 小时前
Rust 调用 C 函数的 FFI
c语言·算法·rust
2401_858286112 小时前
125.【C语言】数据结构之归并排序递归解法
c语言·开发语言·数据结构·算法·排序算法·归并排序
双叶8363 小时前
(C++)学生管理系统(正式版)(map数组的应用)(string应用)(引用)(文件储存的应用)(C++教学)(C++项目)
c语言·开发语言·数据结构·c++
is08155 小时前
STM32的 syscalls.c 和 sysmem.c
c语言·stm32·嵌入式硬件
学不动CV了5 小时前
数据结构---链表结构体、指针深入理解(三)
c语言·arm开发·数据结构·stm32·单片机·链表
百年孤独_7 小时前
LeetCode 算法题解:链表与二叉树相关问题 打打卡
算法·leetcode·链表
算法_小学生7 小时前
LeetCode 75. 颜色分类(荷兰国旗问题)
算法·leetcode·职场和发展
算法_小学生7 小时前
LeetCode 287. 寻找重复数(不修改数组 + O(1) 空间)
数据结构·算法·leetcode
岁忧7 小时前
(LeetCode 每日一题) 1865. 找出和为指定值的下标对 (哈希表)
java·c++·算法·leetcode·go·散列表
alphaTao7 小时前
LeetCode 每日一题 2025/6/30-2025/7/6
算法·leetcode·职场和发展