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++】只知道窗口句柄,如何擦除窗口内容,清理窗口?
c语言·c++·windows
云知谷1 小时前
【经典书籍】C++ Primer 第14类虚函数与多态精华讲解
c语言·开发语言·c++·软件工程·团队开发
爱coding的橙子1 小时前
每日算法刷题Day77:10.22:leetcode 二叉树bfs18道题,用时3h
算法·leetcode·职场和发展
Swift社区1 小时前
LeetCode 404:左叶子之和(Sum of Left Leaves)
算法·leetcode·职场和发展
傻童:CPU2 小时前
C语言需要掌握的基础知识点之递归
c语言·开发语言
一匹电信狗2 小时前
【C++】手搓AVL树
服务器·c++·算法·leetcode·小程序·stl·visual studio
laocooon5238578863 小时前
一个适合新手的训练C题
c语言·开发语言
野蛮人6号4 小时前
力扣热题100道之73矩阵置零
算法·leetcode·矩阵
野蛮人6号4 小时前
力扣热题100道之238除自身以外数组的乘积
算法·leetcode·职场和发展
坚持编程的菜鸟4 小时前
LeetCode每日一题——缀点成线
c语言·算法·leetcode