[Leetcode] 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.
For 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] ]
水。
1 /** 2 * Definition for binary tree 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 void getPath(TreeNode *root, int sum, vector<vector<int> > &res, vector<int> path) { 13 if (root == NULL) { 14 return; 15 } 16 path.push_back(root->val); 17 if (root->left == NULL && root->right == NULL) { 18 if (root->val == sum) { 19 res.push_back(path); 20 } 21 return; 22 } 23 getPath(root->left, sum - root->val, res, path); 24 getPath(root->right, sum - root->val, res, path); 25 } 26 27 vector<vector<int> > pathSum(TreeNode *root, int sum) { 28 vector<vector<int> > res; 29 vector<int> path; 30 getPath(root, sum, res, path); 31 return res; 32 } 33 };