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] ]
刚开始写的程序是这样的:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<vector<int>> pathSum(TreeNode* root, int sum) {
if (root == NULL)
return ret;
tmp.push_back(root->val);
if ((root->left == NULL) && (root->right == NULL))
{
if (sum == accumulate(tmp.begin(), tmp.end(), 0))
ret.push_back(tmp);
}
else
{
if (root->left!=NULL)
pathSum(root->left, sum);
if (root->right!=NULL)
pathSum(root->right, sum);
}
tmp.pop_back();
return ret;
}
private:
vector<vector<int>> ret;
vector<int> tmp;
};
运行时间260ms 左右,看讨论区里的代码和我这类似的,只用16ms ...
最后发现,问题出现在返回值上!
看来copy constructor和析构的过程确实代价很大啊.....
改成下面的形式就快多了:
class Solution {
public:
void pathSum_aux(TreeNode* root, int sum) {
if (root == NULL) return;
tmp.push_back(root->val);
if ((root->left == NULL) && (root->right == NULL))
{
if (sum == root->val)
ret.push_back(tmp);
}
else
{
if (root->left != NULL)
pathSum_aux(root->left, sum - root->val);
if (root->right != NULL)
pathSum_aux(root->right, sum - root->val);
}
tmp.pop_back();
}
vector<vector<int>> pathSum(TreeNode* root, int sum) {
pathSum_aux(root, sum);
return ret;
}
16ms左右...