题目链接:https://leetcode.com/problems/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.
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] ]
思路:一个深度搜索,到叶子节点的时候看和是否等于给定的值即可。
代码如下:
/**
* 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 DFS(TreeNode* root, int sum, vector<int> path, int cur)
{
if(!root) return;
path.push_back(root->val);
if(!root->left && !root->right && cur+root->val==sum) result.push_back(path);
if(!root->left && !root->right) return;
DFS(root->left, sum, path, cur+root->val);
DFS(root->right, sum, path, cur+root->val);
}
vector<vector<int>> pathSum(TreeNode* root, int sum) {
if(!root) return result;
DFS(root, sum, vector<int>(),0);
return result;
}
private:
vector<vector<int>> result;
};