[LeetCode 112 113] - 路径和I & II (Path Sum I & II)
问题
给出一棵二叉树及一个和值,检查该树是否存在一条根到叶子的路径,该路径经过的所有节点值的和等于给出的和值。
例如,
给出以下二叉树及和值22:
5
/ \
4 8
/ / \
11 13 4
/ \ \
7 2 1
函数返回true,因为存在一条根到叶子的路径5->4->11->2,其路径和为22。
初始思路
鉴于题目要求找到一条路径和符合要求即可,选择层次遍历二叉树是一种比较合适的选择-保证了我们首先找到的是最短的路径从而节省了时间。另外由于没有禁止修改原二叉树的值,我们在处理过程中可以把每个点的值修改为到达这点时的路径和,方便比较。至于层次遍历的方法,大家应该已经很熟悉了,使用116,117中的双vector法即可:
class Solution {
public:
bool hasPathSum(TreeNode *root, int sum)
{
if(!root)
{
return false;
}
treeLevel_[].clear();
treeLevel_[].clear();
bool flag = false;
treeLevel_[].push_back(root);
while(!treeLevel_[flag].empty())
{
for(auto iter = treeLevel_[flag].begin(); iter != treeLevel_[flag].end(); ++iter)
{
if(!(*iter)->left && !(*iter)->right)
{
if((*iter)->val == sum)
{
return true;
}
}
if((*iter)->left)
{
(*iter)->left->val += (*iter)->val;
treeLevel_[!flag].push_back((*iter)->left);
}
if((*iter)->right)
{
(*iter)->right->val += (*iter)->val;
treeLevel_[!flag].push_back((*iter)->right);
}
}
treeLevel_[flag].clear();
flag = !flag;
}
return false;
}
private:
std::vector<TreeNode*> treeLevel_[];
};
hasPathSum
提交后Judge Small和Judge Large双双通过。
扩展问题
给出一棵二叉树及一个和值,找出符合条件的所有根到叶子的路径,这些路径经过的所有节点值的和等于给出的和值。
例如,
给出以下二叉树及和值22:
5
/ \
4 8
/ / \
11 13 4
/ \ / \
7 2 5 1
返回
[
[5,4,11,2],
[5,8,4,5]
]
扩展问题初始思路
题目要求找出所有符合条件的路径,意味着不管用什么方法都必须把所有节点遍历一遍。如果还是使用前面的层次遍历,因为是广度优先遍历,需要同时跟踪多条路径的和,直到走到叶子节点。因此在这里我们尝试使用普通的递归中序遍历,由于这是一种深度优先遍历,通过进栈及出栈操作,可以做到一次只需跟踪一条路径即可:
class Solution113 {
public:
std::vector<std::vector<int> > pathSum(TreeNode *root, int sum)
{
result_.clear();
if(!root)
{
return result_;
}
currentPath_.clear();
currentPath_.push_back(root->val);
sum_ = sum;
currentSum_ = root->val;
FindPathSum(root);
return result_;
}
private:
void FindPathSum(TreeNode *node)
{
if(!node->left && !node->right)
{
if(currentSum_ == sum_)
{
result_.push_back(currentPath_);
}
return;
}
if(node->left)
{
currentSum_ += node->left->val;
currentPath_.push_back(node->left->val);
FindPathSum(node->left);
currentSum_ -= node->left->val;
currentPath_.pop_back();
}
if(node->right)
{
currentSum_ += node->right->val;
currentPath_.push_back(node->right->val);
FindPathSum(node->right);
currentSum_ -= node->right->val;
currentPath_.pop_back();
}
}
std::vector<std::vector<int> > result_;
std::vector<int> currentPath_;
int sum_;
int currentSum_;
};
pathSum
提交后同样Judge Small和Judge Large双双通过。
[LeetCode 112 113] - 路径和I & II (Path Sum I & II)的更多相关文章
- Leetcode之动态规划(DP)专题-64. 最小路径和(Minimum Path Sum)
Leetcode之动态规划(DP)专题-64. 最小路径和(Minimum Path Sum) 给定一个包含非负整数的 m x n 网格,请找出一条从左上角到右下角的路径,使得路径上的数字总和为最小. ...
- [LeetCode] #112 #113 #437 Path Sum Series
首先要说明二叉树的问题就是用递归来做,基本没有其他方法,因为这数据结构基本只能用递归遍历,不要把事情想复杂了. #112 Path Sum 原题链接:https://leetcode.com/prob ...
- 【LeetCode】113. 路径总和 II
题目 给定一个二叉树和一个目标和,找到所有从根节点到叶子节点路径总和等于给定目标和的路径. 说明: 叶子节点是指没有子节点的节点. 示例: 给定如下二叉树,以及目标和 sum = 22, 5 / \ ...
- LeetCode:Path Sum I II
LeetCode:Path Sum Given a binary tree and a sum, determine if the tree has a root-to-leaf path such ...
- [Leetcode][JAVA] Path Sum I && II
Path Sum Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that addi ...
- leetcode -day17 Path Sum I II & Flatten Binary Tree to Linked List & Minimum Depth of Binary Tree
1. Path Sum Given a binary tree and a sum, determine if the tree has a root-to-leaf path such tha ...
- LeetCode(124) Binary Tree Maximum Path Sum
题目 Given a binary tree, find the maximum path sum. For this problem, a path is defined as any sequen ...
- Path Sum I && II & III
Path Sum I Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that ad ...
- Path Sum I&&II
I Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up ...
随机推荐
- 高频交易策略之Penny Jump
今天假设有一个笨笨的大型机构投资人(共同基金,银行,退休基金....),他想要买进一只股票,但又不想挂市价买进,所以就在市场里面挂了一张要买进的大单.这时候所有市场里面的人都会看的到limit ord ...
- VMware Ubuntu安装详细过程
参考链接: http://blog.csdn.net/u013142781/article/details/50529030
- Git常用命令清单
创建 在指定目录创建工作仓库,未指定时在当前目录 git init [dir] 创建不包含工作区的仓库 git init --bare 克隆远程仓库到本地 git clone url 配置 git c ...
- 跟Google学习Android开发-起始篇-用碎片构建一个动态的用户界面(3)
4.3 构建一个灵活的用户界面 当设计你的应用程序要支持大范围的屏幕尺寸时,你可以在不同的布局配置中重用碎片,来根据可用的屏幕空间优化用户体验. 例如,在手持设备上,它可能是适应来在一个单窗格用户界面 ...
- cocoa Touch-UIKit
1. 简介: UIKitk框架提供一系列的Class(类)来建立和管理iPhone OS应用程序的用户界面( UI )接口.应用程序对象.事件控制.绘图模型.窗口.视图和用于控制触摸屏等的接口. (P ...
- 关于“无法解析的外部符号”和“该符号在函数_wmain 中被引用”的问题
在VS2008和opendv的环境下: error LNK2019: 无法解析的外部符号_cvDestroyWindow,该符号在函数_wmain 中被引用 error LNK2019: 无法解析的外 ...
- Windows API一日一练(55)FlushFileBuffers和SetFilePointer函数
在PC硬件体系结构里,速度最快的存储器是CPU里面的寄存器,接着到二级缓存,再到系统RAM内存,最后才到硬盘.因为这种体系结构,就决定了操作系统对文件的操作方式,或者说是最优化的算法.比方操作系统接收 ...
- STL之Pairs
什么是Pair 关于类Pair的介绍,下面是引自<C++ Standard Library>的一段话: The class pair is provided to treat two va ...
- MySQL性能调优与架构设计读书笔记
可扩展性设计之数据切分 14.2 数据的垂直切分 如何切分,切分到什么样的程度,是一个比较考验人的难题.只能在实际的应用场景中通过平衡各方面的成本和利益,才能分析出一个真正适合自己的拆分方案. 14. ...
- 如何使用CSS Sprites技术进行图片合并
http://jingyan.baidu.com/article/066074d6757654c3c21cb02d.html