Given a binary tree and a sum, find all root-to-leaf paths where each path‘s sum equals the given sum.
For example:sum = 22,
5
/ 4 8
/ / 11 13 4
/ \ / 7 2 5 1
return
[
[5,4,11,2],
[5,8,4,5]
]
1 class Solution {
2 public:
3 void help(vector<vector<int> >& res, TreeNode* root, vector<int>& path, int target)
4 {
5 TreeNode *left = root->left, *right = root->right;
6 path.push_back(root->val);
7 if (!left && !right && target == root->val)
8 res.push_back(path);
9 if (left)
10 help(res, left, path, target - root->val);
11 if (right)
12 help(res, right, path, target - root->val);
13 path.pop_back();
14 }
15 vector<vector<int>> pathSum(TreeNode* root, int sum) {
16 vector<vector<int> > res;
17 if (!root) return res;
18 vector<int> path;
19 help(res, root, path, sum);
20 return res;
21 }
22 };
Path Sum II (Find Path in Tree) -- LeetCode
原文:http://www.cnblogs.com/fenshen371/p/5170950.html