LeetCode Path Sum II

 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     vector<vector<int> > pathSum(TreeNode *root, int sum) {
13         // Start typing your C/C++ solution below
14         // DO NOT write int main() function
15         vector< vector<int> > t,r;
16         vector<int> v;
17         
18         if(root==0)
19             return r;
20         if(root->left==0&&root->right==0)
21         {
22             if(root->val==sum)
23             {
24                 v.push_back(root->val);
25                 r.push_back(v);
26             }
27             return r;
28         }
29         t.erase(t.begin(),t.end());
30         if(root->left)
31         {
32             t=pathSum(root->left,sum-root->val);
33             if(t.size())
34             {
35                 for(int i=0;i<t.size();i++)
36                 {
37                     t[i].insert(t[i].begin(),root->val);
38                 }
39             }
40             
41         }
42         for(int i=0;i<t.size();i++)
43             r.push_back(t[i]);
44         t.erase(t.begin(),t.end());
45         if(root->right)
46         {
47             t=pathSum(root->right,sum-root->val);
48             if(t.size())
49             {
50                 for(int i=0;i<t.size();i++)
51                 {
52                     t[i].insert(t[i].begin(),root->val);
53                 }
54             }
55         }
56         for(int i=0;i<t.size();i++)
57             r.push_back(t[i]);
58     
59    
60         return r;
61     }
62 };
63 
64 //12ms
65 //84ms

注意局部变量的初始化(清空t)

原文地址:https://www.cnblogs.com/mengqingzhong/p/3052079.html