版权声明:QQ:872289455. WeChat:luw9527. https://blog.csdn.net/MC_007/article/details/80853263
113. Path Sum II
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] ]
深度优先搜索,如果没有找到,返回时要记得删除插入的节点,重新搜索另一条路径,再把另一条路径push_back进去,比较是不是结果,如果还不是还是要清理出来再返回到上一节点,继续往下深搜。
class
Solution {
public:
vector
<vector
<
int
>>
pathSum(TreeNode
* root,
int sum) {
vector
<vector
<
int
>>result;
vector
<
int
>cur;
pathSum(root, sum, cur, result);
return result;
}
void
pathSum(TreeNode
* root,
int sum, vector
<
int
>&cur, vector
<vector
<
int
>>&result) {
if (root
==
nullptr)
return;
cur.
push_back(root->
val);
if (root->
left
==
nullptr
&&root->
right
==
nullptr
&&sum
== root->
val)
result.
push_back(cur);
pathSum(root->
left, sum
- root->
val, cur, result);
pathSum(root->
right, sum
- root->
val, cur, result);
cur.
pop_back();
}
};