【Path Sum II】cpp
题目:
Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.
For 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]
]
代码:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<vector<int>> pathSum(TreeNode* root, int sum) {
vector<vector<int> > ret;
// Terminal conditon 1 : to the null (not leaf node)
// even if sum equals zero at the time, becasue not leaf node
// so it is also not the available solution path
if (!root) return ret;
// Terminal condition 2 : leaf node
if ( !root->left && !root->right )
{
// if leaf node's val equal sum
if ( sum==root->val )
{
vector<int> tmp;
tmp.insert(tmp.begin(),root->val);
ret.push_back(tmp);
}
return ret;
}
// not leaf node : move forward to left and right
vector<vector<int> > l = Solution::pathSum(root->left, sum - root->val);
vector<vector<int> > r = Solution::pathSum(root->right, sum - root->val);
for ( size_t i = ; i<l.size(); ++i )
{
l[i].insert(l[i].begin(), root->val);
ret.push_back(l[i]);
}
for ( size_t i = ; i<r.size(); ++i )
{
r[i].insert(r[i].begin(), root->val);
ret.push_back(r[i]);
}
return ret;
}
};
tips:
与Path Sum思路类似(http://www.cnblogs.com/xbf9xbf/p/4508964.html)
不同的地方是:只要不是leaf node,left和right两边的情况都要考虑。
============================================
并且有个地方需要缕清思路:如果递归时遇上root==NULL,直接返回空的ret是否合理?如果此时的sum==0呢?
root==NULL有以下三种情况
1. 如果整棵树是空树:即使sum==0也不满足条件
2. 某个非leaf node的left(或right)为空:则即使此时sum==0,往left(或right)方向走会得到root=NULL,因为此时root不是leaf node也不成立
============================================
第二次过这道题,DFS的思路比较清晰。头几次漏掉了onePath.push_back(root->val)这个语句,补上以后AC了。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<vector<int> > pathSum(TreeNode* root, int sum)
{
vector<vector<int> > ret;
vector<int> onePath;
if ( root ) Solution::psum(root, sum, ret, onePath);
return ret;
}
static void psum(TreeNode* root, int sum, vector<vector<int> >& ret, vector<int> onePath)
{
if ( !root->left && !root->right )
{
if ( root->val==sum )
{
onePath.push_back(root->val);
ret.push_back(onePath);
return;
}
}
onePath.push_back(root->val);
if ( root->left ) Solution::psum(root->left, sum-root->val, ret, onePath);
if ( root->right ) Solution::psum(root->right, sum-root->val, ret, onePath);
}
};
【Path Sum II】cpp的更多相关文章
- 【二叉树的递归】04找出二叉树中路径和等于给定值的所有路径【Path Sum II】
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 给定一个二叉树和一个和,判断这个树 ...
- 【Combination Sum II 】cpp
题目: Given a collection of candidate numbers (C) and a target number (T), find all unique combination ...
- 【Word Break II】cpp
题目: Given a string s and a dictionary of words dict, add spaces in s to construct a sentence where e ...
- 【Unique Paths II】cpp
题目: Follow up for "Unique Paths": Now consider if some obstacles are added to the grids. H ...
- 【Word Ladder II】cpp
题目: Given two words (start and end), and a dictionary, find all shortest transformation sequence(s) ...
- 【Spiral Matrix II】cpp
题目: Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order. ...
- 【palindrome partitioning II】cpp
题目: Given a string s, partition s such that every substring of the partition is a palindrome. Return ...
- 【Jump Game II 】cpp
题目: Given an array of non-negative integers, you are initially positioned at the first index of the ...
- 【Single Num II】cpp
题目: Given an array of integers, every element appears three times except for one. Find that single o ...
随机推荐
- CentOS学习笔记--vi程序编辑器
vi程序编辑器 Linux里经常需要修改一些配置文件,这时就需要一个编辑器,几乎所有的Linux版本都提供了vi这个编辑器. 文件内容查阅cat命令 如果我们要查阅一个文件的内容时,该如何是好呢?这里 ...
- js设计模式(12)---职责链模式
0.前言 老实讲,看设计模式真得很痛苦,一则阅读过的代码太少:二则从来或者从没意识到使用过这些东西.所以我采用了看书(<js设计模式>)和阅读博客(大叔.alloyteam.聂微东)相结合 ...
- [leetcode]_Longest Common Prefix
问题:寻找最长公共前缀 思路:就是逐一检查每个string中的每一位,碰到不相等的时候,结束:每个string中这一位都相等,加入到common prefix中~ public String long ...
- 魅族MX3问题集锦
我第一台智能机已经服役2年半了,已经满足不了现在日益庞大的APP,所以打算让他光荣退役.我觉得IPhone仍然是目前做的最好的手机,但是对于我来说好像没什么必要,尤其那土豪般的价格.而且我平时看视频居 ...
- 使用@media做自适应
@media (min-width: 768px){ //>=768的设备 } @media (max-width: 1199){ //<=1199的设备 }
- 小米miui5系统的webview在处理动画事件transitionEnd事件时,竟然要用transitionend才行
一般的安卓系统用的是webkitTransitionEnd, 而小米的系统我用了webkitTransitionEnd事件无法执行,只能用transitionend才会被执行,怪
- python Django 学习笔记(四)—— 使用MySQL数据库
1,下载安装MySQLdb类库 http://www.djangoproject.com/r/python-mysql/ 2,修改settings.py 配置数据属性 DATABASES = { 'd ...
- SRF之日志和异常
日志: 日志功能采用log4net实现 log4配置文件在站点目录下的log4net.config. 调用log4写日志的代码如下: log4net.ILog logger = log4net.Log ...
- GNU make 规则
clean : rm *.tmp 规则格式: targets : prerequisites recipe ... targets : prerequisites : recipe recipe .. ...
- 宝马测试(C++实现)
测试目的:对编辑器放大,缩小性能测试. 测试资源:一匹宝马. 测试结果:良好. 实现方法:通过调用本地保存的宝马文件,逐字逐行的显示在编辑器中,并放大,缩小.对不同的符号进 ...