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);
}
相关推荐
nananaij20 分钟前
【LeetCode-02 最小偶倍数 python解法】
python·算法·leetcode
im_AMBER25 分钟前
Leetcode 139 最后一个单词的长度 | 找出字符串中第一个匹配项的下标
开发语言·算法·leetcode
Frostnova丶26 分钟前
(6)LeetCode.42 接雨水
数据结构·算法·leetcode
x_xbx30 分钟前
LeetCode:102. 二叉树的层序遍历
算法·leetcode
DREW_Smile37 分钟前
字符函数和字符串函数2
c语言·开发语言
月明长歌42 分钟前
【码道初阶-Hot100】LeetCode 128. 最长连续序列:从排序双指针扫描到 HashSet,一文讲透为什么 O(n) 解法要用哈希
算法·leetcode·哈希算法
Z9fish1 小时前
C语言算法专题总结(一)排序
c语言·算法·排序算法
Felven1 小时前
B. Roof Construction
c语言
无限进步_1 小时前
深入解析vector:一个完整的C++动态数组实现
c语言·开发语言·c++·windows·git·github·visual studio
Trouvaille ~1 小时前
【贪心算法】专题(六):降维打击与错位重构的终极收官
c++·算法·leetcode·面试·贪心算法·重构·蓝桥杯