#include <iostream>
#include <vector>
using namespace std;
/*
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]
]
*/
void pathSum(TreeNode* root, int sum, vector< vector<int> >& res, vector<int> path) {
if(!root) return;
// push the node into path anyway....
path.push_back(root->val);
if(!(root->right) && !(root->left) && (sum == root->val)) {
res.push_back(path);
}
pathSum(root->left, sum - root->val, res, path);
pathSum(root->right, sum - root->val, res, path);
}
vector< vector<int> > pathSum(TreeNode* root, int sum) {
if(!root) return {};
vector< vector<int> > res;
vector<int> path;
pathSum(root, sum, res, path);
return res;
}
LeetCode 113. Path Sum II
最新推荐文章于 2023-11-14 10:36:43 发布