- Path Sum II
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]
]
【大意】给定一个二叉树和一个目标和,找到所有从根节点到叶子节点路 径总和等于给定目标和的路径
【思路】DFS遍历,从跟到叶子一条一条的递归。
class Solution {
public:
vector<vector<int>> pathSum(TreeNode* root, int sum) {
vector<vector<int>> vvi;
vector < int > vi;
paths(root, sum,vvi,vi);
return vvi;
}
void paths(TreeNode* root, int sum,vector < vector < int > > &vvi,vector < int > &vi)
{
if(root == NULL)
return ;
if( root->val == sum && root->left == NULL && root->right == NULL )
{
vi.push_back(root->val);
vvi.push_back(vi);
vi.pop_back();
return ;
}
vi.push_back(root->val);
paths(root->left,sum-root->val,vvi,vi);
paths(root->right,sum-root->val,vvi,vi);
vi.pop_back();
}
};