【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 ...
随机推荐
- .NET中的IO操作之文件流
读操作 //1.创建文件流 FileStream fsRead =new FileStream("1.txt",FileMode.Open); //2.创建缓冲区,正常情况下,是不 ...
- CentOS学习笔记--基本命令--文件与目录管理
Linux基本命令--文件与目录管理 本节节选自鸟哥的 Linux 私房菜 -- 基础学习篇目录 第七章.Linux 文件与目录管理 ls(文件与目录的检视) ls命令就是list的缩写,ls可以 ...
- c#中判断对象为空的几种方式(字符串等)
(1)先了解几个与空类型相关的关键字和对象 Null : 关键字表示不引用任何对象的空引用,它是所有引用类型变量的默认值,在2.0版本之前也就只有引用变量类型可以为null,如(string a=n ...
- 靶形数独 (codevs 1174)题解
[问题描述] 小城和小华都是热爱数学的好学生,最近,他们不约而同地迷上了数独游戏,好胜的他们想用数独来一比高低.但普通的数独对他们来说都过于简单了,于是他们向Z 博士请教,Z 博士拿出了他最近发明的“ ...
- python网络画图——networkX
networkX tutorial 绘制基本网络图 用matplotlib绘制网络图 基本流程: 1. 导入networkx,matplotlib包 2. 建立网络 3. 绘制网络 nx.draw() ...
- python杂记-3(购买商品)
#!/usr/bin/env python# -*- coding: utf-8 -*-#如下是一个购物程序:#先输入工资,显示商品列表,购买,quit退出,最后格式化输出所买的商品.count = ...
- Android触摸屏配置调试
前几天搞乐蛙时,进入后是鼠标模式,好坑爹的模式有木有~~ 但是大蛋给出了解决方法,我不怕不怕啦~让我们向大牛致敬!!! 首先输入Command查看你的input配置~ adb shell dumpsy ...
- <! [if IE 神奇的条件注释 ]>
早上起来无聊,看到某学长发的一张代码截图有条件注释,正好,研究一下. 条件注释: 在IE中用来区分IE版本.是否为IE的代码神器! 在其他的浏览器里是不好使的. 不过也值得了,IE都区分出来了,其他的 ...
- 包(package) 与 导入(import) 语句剖析
A) 包(package):用于将完成不同功能的类分门别类,放在不同的目录下. B)命名规则:将公司域名翻转作为包名.例如www.vmaxtam.com域名,那么包名就是com.vmaxtam 每个字 ...
- mysql外键设置(待测试)
外键的定义语法:[CONSTRAINT symbol] FOREIGN KEY [id] (index_col_name, ...) REFERENCES tbl_name (index_col ...