[Leetcode Week14]Path Sum II
2024-08-30 20:30:53
Path Sum II 题解
原创文章,拒绝转载
题目来源:https://leetcode.com/problems/path-sum-ii/description/
Description
Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.
Example
Given the below binary tree and sum = 22
5
/ \
4 8
/ / \
11 13 4
/ \ / \
7 2 5 1
return
[
[5,4,11,2],
[5,8,4,5]
]
Solution
class Solution {
void dfs(vector<vector<int>>& res, vector<int>& path, TreeNode* root, int sum) {
if (root -> left == NULL && root -> right == NULL) {
if (sum == root -> val) {
path.push_back(root -> val);
res.push_back(path);
path.pop_back();
}
return;
}
if (root -> left != NULL) {
path.push_back(root -> val);
dfs(res, path, root -> left, sum - (root -> val));
path.pop_back();
}
if (root -> right != NULL) {
path.push_back(root -> val);
dfs(res, path, root -> right, sum - (root -> val));
path.pop_back();
}
}
public:
vector<vector<int>> pathSum(TreeNode* root, int sum) {
vector<vector<int>> res;
if (root == NULL)
return res;
vector<int> path;
dfs(res, path, root, sum);
return res;
}
};
解题描述
这道题目题意是,在一棵二叉树中,寻找一个从根节点到叶子节点的路径,使得路径上的数字之和为给定的数字sum,要求找出所有这样的路径。当然最容易想到的就是使用DFS来解决。
最新文章
- 《寒江独钓_Windows内核安全编程》中修改类驱动分发函数
- 20145223《Java程序设计》第6周学习总结
- lua MVC框架 Orbit初探
- 使用 InstallShield 制作 Delphi 软件安装包
- Boring count(字符串处理)
- poj 1985 Cow Marathon【树的直径裸题】
- 关于MySql链接url参数的设置
- VSTO学习笔记(三) 开发Office 2010 64位COM加载项
- 如何在IDEA中调试 Jar文件
- 聊聊分布式开发 Spring Cloud
- vue 配合vue-resource调用接口,获取数据
- eayUi panel实现上一页下一页
- jQuery.extend(object)
- RedHat 5.6 问题简记
- P2057 [SHOI2007]善意的投票
- RabbitMQ 延时消息队列
- 深入浅出:全面理解SQL Server权限体系
- mongoose实现批量删除和多id查询的api/方法
- Pangolin中opengl的混合(gl_blend)
- 2018春招-今日头条笔试题-第一题(python)
热门文章
- BZOJ 1293 生日礼物(尺取法)
- 【bzoj5108】[CodePlus2017]可做题 拆位+乱搞
- Gevent-socket
- 转:关于Latent Dirichlet Allocation及Hierarchical LDA模型的必读文章和相关代码
- 【题解】SDOI2017树点涂色
- 【刷题】BZOJ 1717 [Usaco2006 Dec]Milk Patterns 产奶的模式
- [JXOI2017]颜色 线段树扫描线 + 单调栈
- [AHOI2009]最小割 最小割可行边&;必须边
- [POI2014]FAR-FarmCraft 树形DP + 贪心思想
- Android 字母导航条实现