问题:
Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.
Note: A leaf is a node with no children.
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] ]
分析:
这道题和Leetcode 112 的不同就是前者要求找出所有的路径,后者只需要判断有没有。不过方法可以通用,这里可以看作很多棵树进行判断,比如对以5为根节点的树判断有没有和为22的路径,就变成了分别对以4和8为根节点的树进行判断有没有和为17的路径。同理可以递归判断。
代码:
/**
* 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>> res;
if( root == NULL ){
return res;
}
//如果刚好相等,检查是不是叶子节点
if( root->val == sum ){
if( root->left == NULL && root->right == NULL ){
vector<int> temp;
temp.insert(temp.begin(),root->val);
res.push_back(temp);
return res;
}
}
//对左右子节点进行递归操作
vector<vector<int>> leftSum = pathSum(root->left,sum- root->val );
vector<vector<int>> rightSum = pathSum(root->right, sum - root->val );
//对返回的结果进行整理,并加入当前节点的值
for( int i = 0 ; i < leftSum.size() ; i ++ ){
vector<int> temp = leftSum[i];
temp.insert(temp.begin(),root->val);
res.push_back(temp);
}
for( int i = 0 ; i < rightSum.size() ; i ++ ){
vector<int> temp = rightSum[i];
temp.insert(temp.begin(),root->val);
res.push_back(temp);
}
return res;
}
};