标签:
Given a binary tree and a sum, find all root-to-leaf paths where each path‘s sum equals the given sum.
For example:sum = 22
,
5 / 4 8 / / 11 13 4 / \ / 7 2 5 1
return
[ [5,4,11,2], [5,8,4,5] ]
Analyse: recursively do the left and right part. When a fraction meets the requirement, push it into the result.
Runtime: 12ms.
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 if(!root) return result; 15 16 vector<int> temp; 17 path(root, sum, result, temp); 18 return result; 19 } 20 void path(TreeNode* root, int gap, vector<vector<int> >& result, vector<int>& temp){ 21 if(!root) return; 22 23 temp.push_back(root->val); 24 if(!root->left && !root->right){ 25 if(root->val == gap) result.push_back(temp); 26 } 27 path(root->left, gap - root->val, result, temp); 28 path(root->right, gap - root->val, result, temp); 29 30 temp.pop_back(); 31 } 32 };
标签:
原文地址:http://www.cnblogs.com/amazingzoe/p/4694861.html