代码改变世界

leetcode - Path Sum II

2013-11-06 10:19  张汉生  阅读(146)  评论(0编辑  收藏  举报

 

 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 getResult (TreeNode * node, vector<vector<int>> & rlt, int target, vector<int> & curPath){
13         target -= node->val;
14         vector<int> path = curPath;
15         path.push_back(node->val);
16         if (node->left==NULL && node->right==NULL && target==0){
17             rlt.push_back(path);
18             return;
19         }
20         if (node->left!=NULL)
21             getResult(node->left, rlt, target, path);
22         if (node->right!=NULL)
23             getResult(node->right, rlt, target, path);
24         return;
25     }
26     vector<vector<int> > pathSum(TreeNode *root, int sum) {
27         // IMPORTANT: Please reset any member data you declared, as
28         // the same Solution instance will be reused for each test case.
29         vector<vector<int> > rlt;
30         if (root==NULL)
31             return rlt;
32         vector<int> path;
33         getResult(root, rlt, sum, path);
34         return rlt;
35     }
36 };