二叉树--路径和为sum的路径方案
原创
©著作权归作者所有:来自51CTO博客作者wx596330ff6d68f的原创作品,请联系作者获取转载授权,否则将追究法律责任
113. Path Sum II
Medium
100636FavoriteShare
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:
class Solution {
private:
vector<vector<int>> result;
int score;
public:
vector<vector<int>> pathSum(TreeNode* root, int sum)
{
score = sum;
if(root == NULL){return result;}
vector<int> tmp;
dfs(root,tmp,0);
return result;
}
void dfs(TreeNode *root,vector<int> tmp,int sum)
{
tmp.push_back(root->val);
sum += root->val;
if(root->left == NULL && root->right == NULL && sum == score){result.push_back(tmp);}
if(root->left != NULL){dfs(root->left,tmp,sum);}
if(root->right != NULL){dfs(root->right,tmp,sum);}
}
};