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来解决。

最新文章

  1. 《寒江独钓_Windows内核安全编程》中修改类驱动分发函数
  2. 20145223《Java程序设计》第6周学习总结
  3. lua MVC框架 Orbit初探
  4. 使用 InstallShield 制作 Delphi 软件安装包
  5. Boring count(字符串处理)
  6. poj 1985 Cow Marathon【树的直径裸题】
  7. 关于MySql链接url参数的设置
  8. VSTO学习笔记(三) 开发Office 2010 64位COM加载项
  9. 如何在IDEA中调试 Jar文件
  10. 聊聊分布式开发 Spring Cloud
  11. vue 配合vue-resource调用接口,获取数据
  12. eayUi panel实现上一页下一页
  13. jQuery.extend(object)
  14. RedHat 5.6 问题简记
  15. P2057 [SHOI2007]善意的投票
  16. RabbitMQ 延时消息队列
  17. 深入浅出:全面理解SQL Server权限体系
  18. mongoose实现批量删除和多id查询的api/方法
  19. Pangolin中opengl的混合(gl_blend)
  20. 2018春招-今日头条笔试题-第一题(python)

热门文章

  1. BZOJ 1293 生日礼物(尺取法)
  2. 【bzoj5108】[CodePlus2017]可做题 拆位+乱搞
  3. Gevent-socket
  4. 转:关于Latent Dirichlet Allocation及Hierarchical LDA模型的必读文章和相关代码
  5. 【题解】SDOI2017树点涂色
  6. 【刷题】BZOJ 1717 [Usaco2006 Dec]Milk Patterns 产奶的模式
  7. [JXOI2017]颜色 线段树扫描线 + 单调栈
  8. [AHOI2009]最小割 最小割可行边&amp;必须边
  9. [POI2014]FAR-FarmCraft 树形DP + 贪心思想
  10. Android 字母导航条实现