[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 ...
随机推荐
- X Window、GNOME和KDE之间的关系
原文地址:http://blog.csdn.net/jincf2011/article/details/6362923 X Window, 即X Windows图形用户接口,它并不是一个软件,而是一个 ...
- setTimeout中所执行函数中的this,永远指向window
注意是要延迟执行的函数中的this哦!! //片段一 setTimeout("alert(this)", 1); // [object Window] //片段二 var obj ...
- ListView列表拖拽排序
ListView列表拖拽排序能够參考Android源代码下的Music播放列表,他是能够拖拽的,源代码在[packages/apps/Music下的TouchInterceptor.java下]. 首 ...
- C++标准库之 Lower_Bound, upper_Bound
关于二分查找,这绝对是最简单却又最难的实现了,其各种版本号能够參见http://blog.csdn.net/xuqingict/article/details/17335833 在C++的标准库中,便 ...
- [week4]每周总结与工作计划
计算机网络 TAT 小白dp 28号还有一场 背单词 背马克思 python目标80% 熟悉coursera c++模版和 仿函数 人文修养 开学数据库,itercast的sql*2 itercast ...
- huffman编码——原理与实现
哈夫曼算法原理 Wikipedia上面说的非常清楚了,这里我就不再赘述,直接贴过来了. 1952年, David A. Huffman提出了一个不同的算法,这个算法能够为不论什么的可能性提供出一个理想 ...
- CSDN挑战编程——《数学问题》
数学问题 题目详情: 给你两个长度为n的正整数序列分别为{a1,a2,a3...an},{b1,b2,b3...bn},0<ai,bi<=100: 设S=max{x1*a1+x2*a2+x ...
- php递归json类实例代码
这篇文章主要介绍了php递归json类的实现方法,可以实现对索引数组及数字数组的解析,进而实现递归数组返回json字符串的功能.具体实现代码如下: <?php /* * @ anthor:QD ...
- LSI MegaCli 命令使用2
#/opt/MegaRAID/MegaCli/MegaCli64 -LDInfo -Lall -aALL 查raid级别#/opt/MegaRAID/MegaCli/MegaCli64 -AdpAll ...
- linux telnet服务安装与配置
关闭防火墙:service iptabls stop chkconfig iptabls off 1.安装telnet服务 [root@rheltest1 ~]# rpm -qa ...