1. Description
2. Solution
2.1 Recursive
代码语言:javascript
复制/**
* 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<vector<int>> result;
if(!root) {
return result;
}
vector<int> path;
tranverseTree(root, sum, result, path);
return result;
}
void tranverseTree(TreeNode* root, int sum, vector<vector<int>>& result, vector<int> path) {
path.push_back(root->val);
if(root->val == sum && root->left == NULL && root->right == NULL) {
result.push_back(path);
}
if(root->left) {
tranverseTree(root->left, sum - root->val, result, path);
}
if(root->right) {
tranverseTree(root->right, sum - root->val, result, path);
}
}
};
代码语言:javascript
复制/**
* 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<vector<int>> result;
if(!root) {
return result;
}
vector<int> path;
tranverseTree(root, sum, result, path);
return result;
}
void tranverseTree(TreeNode* root, int sum, vector<vector<int>>& result, vector<int>& path) {
path.push_back(root->val);
if(root->val == sum && root->left == NULL && root->right == NULL) {
result.push_back(path);
path.pop_back();
return;
}
if(root->left) {
tranverseTree(root->left, sum - root->val, result, path);
}
if(root->right) {
tranverseTree(root->right, sum - root->val, result, path);
}
path.pop_back();
}
};