CoderJesse  
wangjiexi@CS.PKU
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]
]

回溯法。递归周游,同时记录下当前路径上的所有节点。遇到可行的解,将解加入vector。
 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>> *answers = new vector<vector<int>>();
16         vector<int> * cur = new vector<int>();
17         if(root == NULL)
18             return *answers;
19         DepthFirst(root,0,sum,answers,cur);
20         return *answers;
21     }
22     void DepthFirst(TreeNode *root,int s,int sum,vector<vector<int>> * answers,vector<int>* cur)
23     {
24         if(root->left == NULL && root->right == NULL)
25         {
26             if(s + root->val == sum)
27             {
28                 cur->push_back(root->val);
29                 answers->push_back(*cur);
30                 cur->pop_back();
31             }
32         }
33         if(root->left != NULL)
34         {
35             cur->push_back(root->val);
36             DepthFirst(root->left,s+root->val,sum,answers,cur);
37             cur->pop_back();
38         }
39         if(root->right != NULL)
40         {
41             cur->push_back(root->val);
42             DepthFirst(root->right,s+root->val,sum,answers,cur);
43             cur->pop_back();
44         }
45     }    
46 };

 

posted on 2013-03-01 12:39  CoderJesse  阅读(160)  评论(0)    收藏  举报