113. Path Sum II

每日一题 2019 - 04 - 26

题目:

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,

1
2
3
4
5
6
7
      5
/ \
4 8
/ / \
11 13 4
/ \ / \
7 2 5 1

Return:

1
2
3
4
[
[5,4,11,2],
[5,8,4,5]
]

解法:

这个题让找出二叉树上等于给定值和的路径结点,整体来说深度优先遍历就可以解决问题,但是需要注意两个地方:

  • 返回的路径一定是从根节点到最低层的路径记录
  • 每一层完成遍历一定要让当前记录的 vectorsum_value 删除当前层的记录,避免影响进一步的搜索;

代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
/**
* 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<int> now;
vector<vector<int>> res ;
if(root == NULL)
{
return res ;
}
int total_sum = 0;
find_sum(res,now,root,total_sum,sum) ;
return res ;
}
void find_sum(vector<vector<int>>& res , vector<int> now , TreeNode *temp, int &total , int sum)
{
if(temp == NULL)
{
return ;
}
total += temp -> val ;
now.push_back(temp->val);
if(temp-> left == NULL && temp -> right == NULL)
{
if(total == sum)
res.push_back(now);
total -= temp->val;
now.pop_back();
return ;
}
find_sum(res,now,temp->left,total,sum);
find_sum(res,now,temp->right,total,sum);
total -= temp -> val ;
now.pop_back();
return ;
}
};
0%
undefined