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);
}
相关推荐
wen__xvn36 分钟前
代码随想录算法训练营DAY14第六章 二叉树 part02
数据结构·算法·leetcode
Ka1Yan39 分钟前
[数组] - 代码随想录(2-6)
数据结构·算法·leetcode
漫随流水1 小时前
leetcode算法(104.二叉树的最大深度)
数据结构·算法·leetcode·二叉树
恶魔泡泡糖4 小时前
51单片机矩阵按键
c语言·算法·矩阵·51单片机
圣保罗的大教堂4 小时前
leetcode 3453. 分割正方形 I 中等
leetcode
千金裘换酒4 小时前
LeetCode 二叉树的最大深度 递归+层序遍历
算法·leetcode·职场和发展
松涛和鸣4 小时前
DAY52 7-Segment Display/GPIO/Buttons/Interrupts/Timers/PWM
c语言·数据库·单片机·sqlite·html
Echo缘5 小时前
关于在.cpp文件中包含c的头文件,编译报错问题
c语言·开发语言
我是海飞5 小时前
杰理 AC792N WebSocket 客户端例程使用测试教程
c语言·python·单片机·websocket·网络协议·嵌入式·杰理
老鼠只爱大米5 小时前
LeetCode算法题详解 560:和为K的子数组
算法·leetcode·前缀和·哈希表·子数组求和·subarraysum