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);
}
相关推荐
java_nnnn8 小时前
LeetCode刷题滑动窗口(串联所有单词的子串+最小覆盖的子串)Java
算法·leetcode·职场和发展
Navigator_Z9 小时前
LeetCode //C - 1301. Number of Paths with Max Score
c语言·算法·leetcode
学逆向的10 小时前
C 多文件开发
c语言·开发语言·网络安全
学逆向的11 小时前
C 内存属性
c语言·开发语言·算法·网络安全
Zwawa11 小时前
一盏 LED 不够用了:让同一盏灯说出不同的话
c语言·单片机·嵌入式
Nuanyt11 小时前
LeetCode Hot100 刷题笔记 · 普通数组专题
java·笔记·算法·leetcode
老王IT13 小时前
C语言语法基础语法介绍
c语言·开发语言·算法
水饺编程13 小时前
第2章:Linux 基础,在 root 中创建用户账号
linux·c语言·汇编·1024程序员节
春弦_13 小时前
LeetCode Hot 100 刷题笔记
笔记·leetcode·哈希算法
cu14313 小时前
细谈IT6563的具体功能与其应用
c语言·c++·单片机·嵌入式硬件