【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 ...
随机推荐
- [leetcode]_Add Two Numbers
题目:两个链表存储数字,然后求和,和值存储在一个链表中. 代码: public ListNode addTwoNumbers(ListNode l1, ListNode l2) { ListNode ...
- TFS build dotCover StyleCop
FS2010 – Customizing the Build Details View – Summary View http://blogs.msdn.com/b/jpricket/archive/ ...
- Html5元素及基本语法
HTML标签开始标签(opening tag):开放标签结束标签(closing tag):闭合标签 元素定义:HTML元素指的是从开始标签到结束标签的代码(元素以开始标签为起始以借宿标签终止)元素的 ...
- js中forEach无法跳出循环?
1. forEach() forEach() 方法从头至尾遍历数组,为每个元素调用指定的函数.如上所述,传递的函数作为forEach()的第一个参数.然后forEach()使用三个参数调用该 函数:数 ...
- 当数据0跟if判断冲突的时候
我是很无奈的,以后都要2,3,4,5这样去标志状态: 分配状态:<select name="is_send" > <option selected="s ...
- WIN8+VS2013编写发布WCF之二(部署)
上文简介了如何建立WCF工程并且调试,下面说一下如何部署. 本文将陆陆续续讲述三种部署方式,随着项目的进展将不断补全. 声明: 用管理员身份打开VS2013,发布前请将程序的.net版本改成与服务器相 ...
- Oracle并行事务回滚相关参数及视图
/******相关参数****/fast_start_parallel_rollback1.取值有3种:false,low,high2.各值含义:false ---禁用并行回滚功能 ...
- C语言中的堆与栈20160604
首先声明这里说的是C语言中的堆与栈,并不是数据结构中的!一.前言介绍:C语言程序经过编译连接后形成编译.连接后形成的二进制映像文件是静态区域由代码段和数据段(由二部分部分组成:只读数据 段,未初始化数 ...
- rails 学习笔记
bundle package #保存gem到 vendor/cache bundle install –local 从cache从安装 升级rails bundle config –delete ...
- Node.js express路由简单分析
这2天看了一点node+express的路由源码有了一点眉目,总结一下 对于app.get, 首先给出一张类图: 图1 注意每个路由有一个stack,这个stack中存放了Layer. 路由系统内有三 ...