【leetcode】PathSumII
1,991 views
0
Question:
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] ]
Anwser 1:
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: void calPath(TreeNode *root, int sum, vector<int> tmp, vector< vector<int> > &ret){ if(root == NULL){ return; } tmp.push_back(root->val); if(sum == root->val && root->left == NULL && root->right == NULL){ ret.push_back(tmp); } calPath(root->left, sum - root->val, tmp, ret); calPath(root->right, sum - root->val, tmp, ret); tmp.pop_back(); } vector<vector<int> > pathSum(TreeNode *root, int sum) { // Start typing your C/C++ solution below // DO NOT write int main() function vector< vector<int> > ret; if(root == NULL) { return ret; } vector<int> tmp; calPath(root, sum, tmp, ret); return ret; } };
Anwser 2:
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: void calPath(TreeNode *root, int sum, vector<int> tmp, vector< vector<int> > &ret){ if(root == NULL){ return; } tmp.push_back(root->val); if(sum == root->val && root->left == NULL && root->right == NULL){ ret.push_back(tmp); tmp.pop_back(); // pop tmp vector return; } calPath(root->left, sum - root->val, tmp, ret); calPath(root->right, sum - root->val, tmp, ret); tmp.pop_back(); } vector<vector<int> > pathSum(TreeNode *root, int sum) { // Start typing your C/C++ solution below // DO NOT write int main() function vector< vector<int> > ret; if(root == NULL) { return ret; } vector<int> tmp; calPath(root, sum, tmp, ret); return ret; } };
版权所有: 本文系米扑博客原创、转载、摘录,或修订后发表,最后更新于 2013-04-13 12:09:21
侵权处理: 本个人博客,不盈利,若侵犯了您的作品权,请联系博主删除,莫恶意,索钱财,感谢!