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 vector<vector<int> > pathSum(TreeNode *root, int sum) { 2 // IMPORTANT: Please reset any member data you declared, as 3 // the same Solution instance will be reused for each test case. 4 vector<vector<int> > result; 5 result.clear(); 6 if(root == NULL) 7 return result; 8 if(root->val == sum && root->left == NULL && root->right == NULL){ 9 vector<int> tmp(1, sum); 10 result.push_back(tmp); 11 return result; 12 } 13 vector<vector<int> > lresult = pathSum(root->left, sum-root->val); 14 vector<vector<int> > rresult = pathSum(root->right, sum-root->val); 15 int n = lresult.size(); 16 for(int i = 0; i < n; i++){ 17 vector<int> tmp = lresult[i]; 18 tmp.insert(tmp.begin(), root->val); 19 result.push_back(tmp); 20 } 21 n = rresult.size(); 22 for(int i = 0; i < n; i++){ 23 vector<int> tmp = rresult[i]; 24 tmp.insert(tmp.begin(), root->val); 25 result.push_back(tmp); 26 } 27 return result; 28 }