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);
}
相关推荐
时间的拾荒人2 小时前
C语言字符函数与字符串函数完全指南
c语言·开发语言
持力行3 小时前
C/C++ 中的 char*:它标识数组吗?为什么能用下标访问?
c语言·c++
小陈的代码之路6 小时前
回文链表(LeetCode 234)C语言最佳解题思路
c语言·leetcode·链表
aaaameliaaa7 小时前
计算斐波那契数(递归、迭代)(1,1,2,3,5.....)
c语言·开发语言·笔记·算法·排序算法
郭梧悠9 小时前
算法:有效的括号
python·算法·leetcode
旖-旎9 小时前
《LeetCode 1137 第N个泰波那契数 和 LeetCode 三步问题》
c++·算法·leetcode·动态规划
wabs6669 小时前
关于动态规划【力扣718.最长重复子数组的思考】
算法·leetcode·动态规划
zhangfeng11339 小时前
算子开发 Overwrite 覆盖/替换模式 Accumulate 累加模式,性能对比 memset错误 bat_alloc 错误
c语言·人工智能·gnu·算子开发
SuperByteMaster10 小时前
JLinkDevices.xml FLM文件路径不对
c语言
LDR00610 小时前
LDR6500赋能POS机底座:单口Type-C供电、维护与产测一体化解决方案
大数据·c语言·人工智能