题目链接:https://leetcode.com/problems/path-sum-ii/
Runtimes:93ms
1、问题
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]
]
2、分析
之前写过一篇path sum I,比较简单,而这道题是升级版,传统的思维需要记录过程中扫描过的每一个分支。这样子比较繁琐,因此跑出来的时间会比较大。有待继续提高。
3、小结
需要多加一个记录扫描分支的tracker,因此增加了处理时间。
4、实现
/**
* Definition for binary tree
* 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) {
vector <int> iv;
vector <TreeNode *> tv;
vector < vector <int> > tracker;
vector < vector <int> > result;
if(root == NULL)
return result;
iv.push_back(root->val);
tv.push_back(root);
tracker.push_back(iv);
while(iv.size() > 0 && tv.size() > 0)
{
int val = iv.back(); iv.pop_back();
TreeNode * p = tv.back(); tv.pop_back();
vector <int> tempv = tracker.back(); tracker.pop_back();
if(val == sum && p->left == NULL && p->right == NULL)
{
result.push_back(tempv);
}
if(p->right != NULL)
{
iv.push_back(val + p->right->val);
tv.push_back(p->right);
vector <int> rv = tempv;
rv.push_back(p->right->val);
tracker.push_back(rv);
}
if(p->left != NULL)
{
iv.push_back(val + p->left->val);
tv.push_back(p->left);
vector <int> lv = tempv;
lv.push_back(p->left->val);
tracker.push_back(lv);
}
}
return result;
}
};
5、反思
有更好的解,等看过 编程之美后再来重新思考。vector pop_back()返回空值,back()才是返回最后一个值。
文章链接:http://blog.csdn.net/shawjan/article/details/44196989