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);
}
相关推荐
墨染千千秋1 小时前
C/C++ Keywords
c语言·c++
爱编码的小八嘎5 小时前
C语言完美演绎9-23
c语言
happymaker06265 小时前
简单LRU的实现(基于LinkedHashMap)
算法·leetcode·lru
普通网友5 小时前
《算法面试必刷:15 个高频 LeetCode 题(附代码)》
算法·leetcode·面试
_深海凉_5 小时前
LeetCode热题100-搜索二维矩阵
算法·leetcode·矩阵
我不是懒洋洋6 小时前
手写一个KMP算法:从原理到工程级实现
c语言
代码中介商6 小时前
C语言链表完全指南:从单节点到链表管理
c语言·算法·链表
『昊纸』℃6 小时前
C语言程序设计从入门到进阶【比特鹏哥c语言2023完整版视频教程】(c语言基础入
c语言·函数·常量·编程教程·变量作用域
凉、介8 小时前
Armv8-A virtualization 笔记 (一)
c语言·笔记·学习·嵌入式·虚拟化·hypervisor
♛识尔如昼♛9 小时前
C 进阶(3) - 文件和目录
c语言·文件和目录