Description:
Given a binary tree, find all paths that sum of the nodes in the path equals to a given number target.
Note:
1.a valid path的定义是 from root node to any of the leaf nodes.所以当满足target条件时还要判断最后一个结点的左右子树是否为空(啊每次都不认真审题要注意啊)
2.注意函数getSum中的sum和path是不加引用,而result是加引用的,因为sum和path在递归中是不共享的,每次更新只作为参数传递下去,而result需要在递归中共享结果。
Given a binary tree, find all paths that sum of the nodes in the path equals to a given number target.
Note:
1.a valid path的定义是 from root node to any of the leaf nodes.所以当满足target条件时还要判断最后一个结点的左右子树是否为空(啊每次都不认真审题要注意啊)
2.注意函数getSum中的sum和path是不加引用,而result是加引用的,因为sum和path在递归中是不共享的,每次更新只作为参数传递下去,而result需要在递归中共享结果。
Code:
class Solution {
void getSum(TreeNode* root, int target, int sum, vector<int> path, vector<vector<int>>& result) {
if (!root)
return;
if (root->val + sum == target && !root->left && !root->right) {
path.push_back(root->val);
result.push_back(path);
return;
}
sum += root->val;
path.push_back(root->val);
getSum(root->left, target, sum, path, result);
getSum(root->right, target, sum, path, result);
return;
}
public:
/**
* @param root the root of binary tree
* @param target an integer
* @return all valid paths
*/
vector<vector<int>> binaryTreePathSum(TreeNode *root, int target) {
// Write your code here
vector<vector<int>> result;
vector<int> path;
int sum = 0;
getSum(root, target, sum, path,result);
return result;
}
};