【LeetCode & 剑指offer刷题】树题9:34 二叉树中和为某一值的路径(112. Path Sum)
【LeetCode & 剑指offer 刷题笔记】目录(持续更新中...)
112. Path Sum
Given a binary tree and a sum, determine if the tree has
a root-to-leaf path
such that adding up all the values along the path equals the given sum.
Note:
A leaf is a node with no children.
Example:
Given the below binary tree and
sum = 22
,
5
/
\
4
8
/
/ \
11
13 4
/
\
\
7
2
1
return true, as there exist a root-to-leaf path
5->4->11->2
which sum is 22.
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
/*
只要求返回true或false,因此不需要记录路径
*/
class
Solution
{
public
:
bool
hasPathSum
(
TreeNode
*
root
,
int
sum
)
{
if
(
root
==
nullptr
)
return
false
;
if
(
root
->
left
==
nullptr
&&
root
->
right
==
nullptr
)
//叶子结点
return
sum
==
root
->
val
;
int
newsum
=
sum
-
root
->
val
;
return
hasPathSum
(
root
->
left
,
newsum
)
||
hasPathSum
(
root
->
right
,
newsum
);
}
};
113
.
Path Sum II
Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.
Note:
A leaf is a node with no children.
Example:
Given the below binary tree and
sum = 22
,
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) {}
* };
*/
/*
求所有和等于某数的路径
*/
#include
//算容器类元素和可用accumulate函数
class
Solution
{
public
:
vector
<
vector
<
int
>>
pathSum
(
TreeNode
*
root
,
int
sum
)
{
vector
<
vector
<
int
>>
result
;
vector
<
int
>
path
;
path_sum
(
root
,
path
,
result
,
sum
);
return
result
;
}
private
:
void
path_sum
(
TreeNode
*
root
,
vector
<
int
>&
path
,
vector
<
vector
<
int
>>&
result
,
int
gap
)
{
if
(
root
==
nullptr
)
return
;
//递归出口
else
path
.
push_back
(
root
->
val
);
//
存储结点元素到path
if
(
root
->
left
==
nullptr
&&
root
->
right
==
nullptr
)
//叶子结点时push path到结果向量中
{
if
(
gap
==
root
->
val
)
result
.
push_back
(
path
);
//如果该path和为sum则push到结果向量中(这里用sum累减路径上的元素,得到gap与路径上最后一个元素比较,节省时间,如果得到path再accumulate,则会造成不同路径间的重复计算)
// return; //递归出口,到叶结点后退出,(不能写这句,还需运行到结尾进行pop)
}
path_sum
(
root
->
left
,
path
,
result
,
gap
-
root
->
val
);
//沿深度方向遍历
path_sum
(
root
->
right
,
path
,
result
,
gap
-
root
->
val
);
path
.
pop_back
();
//
删除最后一个元素
,腾出空间(本函数中只push了一次,故只需pop一次)
}
};
posted @
2019-01-05 19:44 wikiwen 阅读(
...) 评论(
...) 编辑 收藏