113. Path Sum II
来源:互联网 发布:javascript入门难吗 编辑:程序博客网 时间:2024/06/04 08:05
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]]
这一题和112题思路是一样的,只是多了一些引用的参数,因为这一次需要保存所有等于sum的路径。所以在递归时并不是找到一条路径就返回true,而是要全部访问完才可以,代码如下。
Code(LeetCode运行13ms)
/** * 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) { vector<vector<int>> result; vector<int> aPath; hasPath(root, sum, aPath, result); return result; } void hasPath(TreeNode *root, int sum, vector<int> &aPath, vector<vector<int>> &result) { if (!root) { return; } aPath.push_back(root -> val); if (!root -> left && !root -> right && sum == root -> val) { result.push_back(aPath); } hasPath(root -> left, sum - root -> val, aPath, result); hasPath(root -> right, sum - root -> val, aPath, result); aPath.pop_back(); }};
阅读全文
0 0
- 113. Path Sum II
- 113. Path Sum II
- 113. Path Sum II
- 113. Path Sum II
- 113. Path Sum II
- 113. Path Sum II
- 113. Path Sum II
- 113. Path Sum II
- 113. Path Sum II
- 113. Path Sum II
- 113. Path Sum II
- 113. Path Sum II
- 113. Path Sum II
- 113. Path Sum II
- 113. Path Sum II
- 113. Path Sum II
- 113. Path Sum II
- 113. Path Sum II
- framebuffer 应用层函数
- HDU 4970 Killing Monsters(树状数组 || 思维)
- IP 地址聚合 经典算法 已经过验证
- Scheduler模块详解
- FreeMarker日期打印不出来
- 113. Path Sum II
- 利用matlab2017进行深度学习
- VS2010 导入应用程序 exe 调试 DLL
- linux上配置apache各种功能
- Selenium使用Firefox测试SSL页面反复提示不信任问题
- 对超大数求余
- ${pageContext.request.contextPath}和<%=request.getContextPath()%>
- logstash的坑:不能重复读一份完全相同的文件!
- hdu 2191 多重背包入门