题目:
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] ]
解释:
这道题和I不一样,I只需要返回是否存在即可,这道题目需要保存路径,所以还是需要另外写一个dfs的,把当前路径的总和也当做参数传进去,可以节省求和的时间
python代码:
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def pathSum(self, root, sum):
"""
:type root: TreeNode
:type sum: int
:rtype: List[List[int]]
"""
self.result=[]
def dfs(root,path,s):
path.append(root.val)
s+=root.val
if not root.left and not root.right and s==sum:
self.result.append(path[:])
if root.left:
dfs(root.left,path,s)
if root.right:
dfs(root.right,path,s)
path.pop()
if root:
dfs(root,[],0)
return self.result;
c++代码:
/**
* 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>>result;
vector<vector<int>> pathSum(TreeNode* root, int sum) {
vector<int>path;
if (root)
dfs(root,path,0,sum);
return result;
}
void dfs(TreeNode* root,vector<int>& path,int s,int sum)
{
path.push_back(root->val);
s+=root->val;
if(!root->left &&!root->right&& s==sum)
{
vector<int>new_path(path);
result.push_back(new_path);
}
if(root->left)
dfs(root->left,path,s,sum);
if(root->right)
dfs(root->right,path,s,sum);
path.pop_back();
}
};
总结:
注意,由于函数参数传递list的时候,传递的是引用,所以就算是加到了result中,在dfs的过程中如果path被改变,result也会相应地改变,所以,需要用一个新的list保存path后再传入result中。
?为什么path需要复原而s不需要?
因为path是引用而s不是,path会影响外面的值而s不会。