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);
}
相关推荐
wuminyu10 小时前
OpenJDK学习笔记:Native事件队列与Java回调背压
java·linux·c语言·jvm·c++
Matt Feng11 小时前
STM32多路SWD烧录:并行下载与5类连接故障排查
c语言·stm32·单片机·嵌入式硬件
小灰灰搞电子14 小时前
C/C++ 的大小端是什么?一个整数在内存里究竟怎么存储?
c语言·arm开发·c++
嵌入式 Linux手记14 小时前
静态库动态库到底差在哪
linux·c语言·嵌入式
Shaoshing15 小时前
LeetCode 921.使括号括号有效的最少添加
java·算法·leetcode·职场和发展
圣保罗的大教堂17 小时前
leetcode 3884. 双端字符匹配 简单
leetcode
jianqiang.xue17 小时前
STM32 STOP 模式唤醒后串口和外设全哑,问题不在唤醒源
c语言·stm32·单片机·嵌入式硬件·嵌入式·ai编程·代码审查
烟烟Abandon17 小时前
FFmpeg开发基础之 C 语言中的循环语句
c语言·ffmpeg
金榜题名萱19 小时前
蓝桥杯 - 妮妮的月饼工厂(二分)
c语言·数据结构·c++·算法·蓝桥杯·动态规划
Shaoshing21 小时前
LeetCode100 76.最小覆盖字串
java·算法·leetcode