每日两题 / 437. 路径总和 III && 105. 从前序与中序遍历序列构造二叉树(LeetCode热题100)

437. 路径总和 III - 力扣(LeetCode)

前序遍历时,维护当前路径(根节点开始)的路径和,同时记录路径上每个节点的路径和

假设当前路径和为cur,那么ans += 路径和(cur - target)的出现次数

cpp 复制代码
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    unordered_map<long long, int> mp;
    long long ans = 0;
    long long t;
    void dfs(TreeNode *root, long long &cur) {
        if (root == nullptr) return;
        cur += root->val;
        ans += mp[cur - t] ;
        mp[cur] ++ ;
        dfs(root->left, cur);
        dfs(root->right, cur);
        mp[cur] -- ;
        cur -= root->val;
    }
    int pathSum(TreeNode* root, int targetSum) {
        mp[0] ++ ;
        t = targetSum;
        long long cur = 0;
        dfs(root, cur);
        return ans;
    }
};

105. 从前序与中序遍历序列构造二叉树 - 力扣(LeetCode)

递归构造,每次构造子树的根节点

根节点的左右子节点如何构造?根据中序遍历中,根节点的位置确定左右子树节点数量

在前序遍历中,分别确定左右子树节点的范围,两者的第一个节点就是根节点的左右节点

cpp 复制代码
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left),
 * right(right) {}
 * };
 */
class Solution {
public:
    unordered_map<int, int> mp;
    TreeNode* dfs(vector<int> &preorder, vector<int> &inorder, int l, int r, int ll, int rr) {
        if (l > r) return nullptr;
        TreeNode *root = new TreeNode(preorder[l]);
        int iidx = mp[preorder[l]];
        int sz = iidx - ll;
        root->left = dfs(preorder, inorder, l + 1, l + sz, ll, iidx - 1);
        root->right = dfs(preorder, inorder, l + sz + 1, r, iidx + 1, rr);
        return root;
    }
    TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
        int n = preorder.size();
        for (int i = 0; i < inorder.size(); ++ i)
            mp[inorder[i]] = i;
        return dfs(preorder, inorder, 0, n - 1, 0, n - 1);
    }
};
相关推荐
Dola_Zou5 小时前
工厂智能排产软件算法保护与按产线计费实战
算法·自动化·软件工程·软件加密
啦啦啦啦啦zzzz6 小时前
Logger的组装(c++20)
c++·算法·c++20
尾善爱看海7 小时前
前端算法与手写题集
前端·算法
程序员阿鹏8 小时前
为什么MySQL InnoDB选择B+树?
数据结构·数据库·b树·sql·mysql·算法·缓存
AI 思录8 小时前
Prompt 事故档案(八):日常表达被标为“待校准”,AI 的爹味语法从哪里来
大数据·人工智能·算法·prompt·用户体验·ai合规
月光船幽幽8 小时前
跨范式映射的稳定接口设计
人工智能·python·算法
2601_965742229 小时前
全媒体运营与短视频代运营,两者有什么区别?
大数据·数据结构·人工智能·算法·ai·媒体
wordbaby10 小时前
混合检索:两全其美的艺术
人工智能·算法
彧azz11 小时前
数据结构:关于图的学习
c语言·数据结构·笔记·学习·算法
热心网友俣先生11 小时前
A题-药材的烘干问题-题意逐句翻译
算法·数学建模