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);
}
相关推荐
你怎么知道我是队长几秒前
C语言---排序算法11---桶排序法
c语言·开发语言·排序算法
橘色的喵9 小时前
现代 C++17 相比 C 的不可替代优势
c语言·c++·现代c++·c++17
浅念-10 小时前
C/C++内存管理
c语言·开发语言·c++·经验分享·笔记·学习
Mr YiRan10 小时前
函数指针与指针运算
c语言
sprintzer11 小时前
2.06-2.15力扣数学刷题
算法·leetcode·职场和发展
滴滴答滴答答12 小时前
LeetCode Hot100 之 17 有效的括号
算法·leetcode·职场和发展
老鼠只爱大米13 小时前
LeetCode经典算法面试题 #20:有效的括号(数组模拟法、递归消除法等五种实现方案详细解析)
算法·leetcode··括号匹配·数组模拟法·递归消除法
不想看见40413 小时前
6.3Permutations -- 回溯法--力扣101算法题解笔记
笔记·算法·leetcode
敲皮裤的代码14 小时前
《C语言》深入理解指针(4)
c语言
J-TS14 小时前
线性自抗扰控制LADRC
c语言·人工智能·stm32·单片机·算法