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]
]
分析:
這道題目算是Path Sum的延伸,只不過要求出所有從根到樹葉的路徑上節點和為給定值的路徑,並放到一個vector中返回。采取類似於Path Sum遞歸思路,每次遞歸都會建立一個新的vector,復制之前的vector內容,並將當前節點的值放入,如果當前節點是葉節點,並且路徑上節點和滿足要求,就將新的vector放入最終返回的vector中。
代碼:
class Solution {
public:
vector> res;
vector> pathSum(TreeNode* root, int sum) {
if(!root)
return res;
vector tmp;
pathSum1(root,sum,tmp);
return res;
}
void pathSum1(TreeNode* root, int sum,vector tmp)
{
if(!root)
return ;
vector tmp1;
tmp1 = tmp;
tmp1.push_back(root->val);
if(!root->left&&!root->right)
{
if(root->val==sum)
res.push_back(tmp1);
return;
}
pathSum1(root->left,sum-root->val,tmp1);pathSum1(root->right,sum-root->val,tmp1);
}
};