原题:https://leetcode.com/problems/path-sum-ii/description/
题目描述:
Given a binary tree and a sum, find all root-to-leaf paths where each path’s sum equals the given sum.
For 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]
]
题解
和上一题解题思路一样。每次递归时,都将新的节点的值存入当前vector< int >中。如果当前节点是叶子节点且路径和等于sum,那就将当前vector< int >存入一个vector< vector< int >>变量中。因为每次递归vector< int >变量使用的都不是引用,所以每次调用递归时都会在函数中生成一个传递参数的副本,虽然浪费空间但是正好适合递归的做法。
代码:
/**
* 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:
void findPath(TreeNode* root, int sum, vector<int> v, vector<vector<int>>& vs) {
if (!root) return;
v.push_back(root->val);
if (root->val == sum&&!root->left&&!root->right) vs.push_back(v);
sum -= root->val;
findPath(root->left, sum, v, vs);
findPath(root->right, sum, v, vs);
vector<int>().swap(v);
}
vector<vector<int>> pathSum(TreeNode* root, int sum) {
vector<vector<int>> vs;
findPath(root, sum, vector<int>(), vs);
return vs;
}
};
114 / 114 test cases passed.
Status: Accepted
Runtime: 12 ms`