113. 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 class Solution {
 2 public:
 3     vector<vector<int>> res;
 4     void backtrack(TreeNode* root, int cursum, int targetSum ,vector<int>& path) {
 5         if (root == nullptr) return;
 6         if (root->left == nullptr && root->right == nullptr) {
 7             if (root->val + cursum == targetSum ) {
 8                 path.emplace_back(root->val);
 9                 res.emplace_back(path);
10                 path.pop_back();
11 
12             }
13             return;
14         }
15         path.emplace_back(root->val);
16         backtrack(root->left,cursum+root->val,targetSum,path);
17         backtrack(root->right,cursum+root->val,targetSum,path);
18         path.pop_back();
19 
20     }
21     vector<vector<int>> pathSum(TreeNode* root, int targetSum) {
22         vector<int> path;
23         backtrack(root,0,targetSum,path);
24         return res;
25     }
26 };

 

 

posted @ 2018-01-29 22:04  乐乐章  阅读(153)  评论(0编辑  收藏  举报