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 a binary tree node.
 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     vector<vector<int>> pathSum(TreeNode* root, int sum) {
13         vector<vector<int>> result;
14         vector<int> path;
15         dfs(root,sum,path,result);
16         return result;
17         
18     }
19     
20     void dfs(TreeNode *root,int gap,vector<int> &path,vector<vector<int>> &result)
21     {
22         if(root==NULL) return;
23         
24         path.push_back(root->val);
25         if(!root->left&&!root->right&&gap==root->val)
26             result.push_back(path);
27         dfs(root->left,gap-root->val,path,result);
28         dfs(root->right,gap-root->val,path,result);
29         path.pop_back();
30     }
31 };

 

posted @ 2015-08-28 10:20  尾巴草  阅读(147)  评论(0编辑  收藏  举报