Path Sum III
来源:互联网 发布:cf积分刷点卷软件 编辑:程序博客网 时间:2024/06/07 04:42
给定一个定值和一个二叉树,要求返回路径之和等于定值的条数,可以不从头节点开始
struct TreeNode { int val; TreeNode *left; TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {} };参考discuss
class Solution {public: int help(TreeNode* root, int sum, unordered_map<int, int>& store, int pre) { if (!root) return 0; root->val += pre; int res = (root->val == sum) + (store.count(root->val - sum) ? store[root->val - sum] : 0); store[root->val]++; res += help(root->left, sum, store, root->val) + help(root->right, sum, store, root->val); store[root->val]--; return res; } int pathSum(TreeNode* root, int sum) { unordered_map<int, int> store; return help(root, sum, store, 0); }};用关联容器记录从根节点开始到某个节点的权值之和,当有这样的路径出现时,用关联容器的关键值减去定值sum,差值必然会出现在关联容器中
0 0
- 437. Path Sum III
- 437. Path Sum III
- 437. Path Sum III
- Path Sum III
- 437. Path Sum III
- 437. Path Sum III
- Path Sum III
- 437. Path Sum III
- LeetCode-Path Sum III
- path sum iii-leetcode
- Path Sum III ---LeetCode
- Leetcode | Path Sum III
- 437. Path Sum III
- 437. Path Sum III
- LeetCode437. Path Sum III
- Leetcode Path Sum III
- 437. Path Sum III
- 437. Path Sum III*
- Unity5.x AssetsBundle笔记
- 【工具】Glide基本使用方法说明与圆角图片工具
- shell脚本不可以执行原因
- 剑指offer-25 二叉树中和为某一值的路径
- 如何查看某个端口被谁占用
- Path Sum III
- 初学者的MySQL 1067 错误解决方法
- 【Dubbo】dubbo连接zookeeper注册中心因为断网导致线程无限等待问题
- C#学习日记 字典
- Java SE、Java EE、Java ME三者的区别
- 概率计算 蓝桥杯 C语言
- HTML5+CSS3整体回顾
- markdown入门
- LaTeX字体设置