原題:
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]
]
解題:
其實就是求圖中等於某個sum的路徑,遞歸前序遍歷樹,每次遍歷到葉子節點的時候判斷當前的路徑上所有節點值的和是否爲sum,如果是的話就保存到vector
/**
* 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 {
vector<vector<int>> ret;
public:
void pathSum(TreeNode* root, vector<int> path, int sum) {
path.push_back(root->val);
if(!root->left && !root->right){
if((sum - root->val)== 0)
ret.push_back(path);
}
if(root->left){
pathSum(root->left, path, sum - root->val);
}
if(root->right){
pathSum(root->right, path, sum - root->val);
}
}
vector<vector<int>> pathSum(TreeNode* root, int sum) {
if(root){
vector<int> path;
pathSum(root, path, sum);
}
return ret;
}
};