题目:

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的更多相关文章

  1. 【二叉树的递归】04找出二叉树中路径和等于给定值的所有路径【Path Sum II】

    ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 给定一个二叉树和一个和,判断这个树 ...

  2. 【Combination Sum II 】cpp

    题目: Given a collection of candidate numbers (C) and a target number (T), find all unique combination ...

  3. 【Word Break II】cpp

    题目: Given a string s and a dictionary of words dict, add spaces in s to construct a sentence where e ...

  4. 【Unique Paths II】cpp

    题目: Follow up for "Unique Paths": Now consider if some obstacles are added to the grids. H ...

  5. 【Word Ladder II】cpp

    题目: Given two words (start and end), and a dictionary, find all shortest transformation sequence(s) ...

  6. 【Spiral Matrix II】cpp

    题目: Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order. ...

  7. 【palindrome partitioning II】cpp

    题目: Given a string s, partition s such that every substring of the partition is a palindrome. Return ...

  8. 【Jump Game II 】cpp

    题目: Given an array of non-negative integers, you are initially positioned at the first index of the ...

  9. 【Single Num II】cpp

    题目: Given an array of integers, every element appears three times except for one. Find that single o ...

随机推荐

  1. JavaScript的闭包是什么意思以及作用和应用场景

    JavaScript闭包 1.什么是闭包 百度百科对于闭包的解释是:闭包是指可以包含自由(未绑定到特定对象)变量的代码块:这些变量不是在这个代码块内或者任何全局上下文中定义的,而是在定义代码块的环境中 ...

  2. LevelDB源码之五Current文件\Manifest文件\版本信息

    版本信息有什么用?先来简要说明三个类的具体用途: Version:代表了某一时刻的数据库版本信息,版本信息的主要内容是当前各个Level的SSTable数据文件列表. VersionSet:维护了一份 ...

  3. OJ推荐【转】

    来自:http://blog.csdn.net/zdp072/article/details/16207111 一. Online Judge简介: Online Judge系统(简称OJ)是一个在线 ...

  4. async/await的实质理解

    async/await关键字能帮助开发者更容易地编写异步代码.但不少开发者对于这两个关键字的使用比较困惑,不知道该怎么使用.本文就async/await的实质作简单描述,以便大家能更清楚理解. 一.a ...

  5. 关于FragmentManager findFragmentById 返回nul

    先看Fragment的两种生成方式 一.用xml标签生成 在fragment的宿主activity中添加xml标签 <fragment android:id="@+id/fragmen ...

  6. 8.python中的数字

    python中数字对象的创建如下, a = 123 b = 1.23 c = 1+1j 可以直接输入数字,然后赋值给变量. 同样也可是使用类的方式: a = int(123) b = float(1. ...

  7. 关于Cygwin——包管理、替换默认终端、同MSYS的比较

    (搬运自我在SegmentFault的博客) Cygwin 是一个用于 Windows 的类 UNIX shell 环境. 它由两个组件组成:一个 UNIX API 库,它模拟 UNIX 操作系统提供 ...

  8. Supporting Connected Routes to Subnet Zero

    Supporting Connected Routes to Subnet Zero IOS allows the network engineer to tell a router to eithe ...

  9. Android--WebView的一些配置项

    //打开页面时,自适应屏幕 wv_showWeb_webActivity.getSettings().setUseWideViewPort(true);//设置此属性可以任意比例缩放 wv_showW ...

  10. 黑客群体的露面说明互联网公司开始回馈IT行业了,

    揭开中国黑客群体的神秘面纱 年薪数百万 2015-04-26 09:59:45 15259 次阅读 14 次推荐 稿源:经济观察报 33 条评论   在网络世界有专属的代号,那里才是他们最习惯的“世界 ...