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]
]

这题是在Path Sum的基础上稍作修改。

与上题增加的动作是保存当前stack中路径的加和curSum。

当curSum等于sum时,将cur加入ret。

/**
* 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<vector<int> > ret;
if(!root)
return ret; stack<TreeNode*> stk;
vector<int> cur;
cur.push_back(root->val);
int curSum = root->val;
unordered_map<TreeNode*, bool> visited;
stk.push(root);
visited[root] = true; while(!stk.empty())
{
TreeNode* top = stk.top();
if(!top->left && !top->right)
{//leaf
if(curSum == sum)
ret.push_back(cur);
} if(top->left && visited[top->left] == false)
{
stk.push(top->left);
visited[top->left] = true;
cur.push_back(top->left->val);
curSum += top->left->val;
continue;
}
if(top->right && visited[top->right] == false)
{
stk.push(top->right);
visited[top->right] = true;
cur.push_back(top->right->val);
curSum += top->right->val;
continue;
} stk.pop();
curSum -= top->val;
cur.pop_back();
}
return ret;
}
};

最新文章

  1. Xcode UUID查询
  2. Yii2的深入学习--别名(Aliases)
  3. css学习笔记 1
  4. php二位数组合并
  5. 从一个action地址获取信息
  6. numpy中的broadcast
  7. mysql 。。。
  8. DNS的查找机制、中文扩展,及其对手机扫描商标名称的支持
  9. 分支-15. 日K蜡烛图(15)
  10. Python 接口测试(一)
  11. Android特效专辑(四)——APP主页框架TabHost绑定ViewPager的替换者TabLayout
  12. 为什么HashMap初始大小为16,为什么加载因子大小为0.75,这两个值的选取有什么特点?
  13. ssl证书
  14. 数据类型&amp;字符串得索引及切片
  15. R-TREE
  16. POJ1125-Stockbroker Grapevine【Floyd】(模板题)
  17. innodb表锁情况
  18. 离线应用与客户端存储(cookie storage indexedDB)
  19. python线程死锁与递归锁
  20. 【转】Android实战技巧之四十九:Usb通信之USB Host

热门文章

  1. 使用Spring配置shiro时,自定义Realm中属性无法使用注解注入解决办法
  2. [制作实践]一种基于LM2576的多功能开关电源设计
  3. mysql知识点(三)
  4. 一些值得学习的Unity教程 (很实用的包括源码)
  5. 第一篇 对Javascript中原型的深入理解
  6. Sql语句-case when then else end
  7. 多种非接触卡 ATQA 字节说明
  8. [Todo] solr, lucence等学习
  9. Backup and restore of FAST Search for SharePoint 2010
  10. 《Pro JavaScript Techniques》中的一些函数