[Leetcode] #113 Path Sum II
来源:互联网 发布:微信网络错误 编辑:程序博客网 时间:2024/06/03 15:51
Discription:
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]]
Solution:
采用DFS,给出两种稍微不同的递归写法。
写法一:
void pathSum(TreeNode* root, int sum, vector<int> &path, vector<vector<int>> &res){path.push_back(root->val);sum -= root->val;if (sum == 0 && !root->left && !root->right)res.push_back(path);if (root->left)pathSum(root->left, sum, path, res);if (root->right)pathSum(root->right, sum, path, res);path.pop_back();}vector<vector<int>> pathSum(TreeNode* root, int sum) {vector<vector<int>> ans;if (!root) return ans;vector<int> path;pathSum(root, sum, path, ans);return ans;}
写法二:
void pathSum(TreeNode* root, int sum, vector<int> &path, vector<vector<int>> &res){if (!root) return;path.push_back(root->val);sum -= root->val;if (sum == 0 && !root->left && !root->right)res.push_back(path);pathSum(root->left, sum, path, res);pathSum(root->right, sum, path, res);path.pop_back();}vector<vector<int>> pathSum(TreeNode* root, int sum) {vector<vector<int>> ans;vector<int> path;pathSum(root, sum, path, ans);return ans;}
0 0
- LeetCode 113: Path Sum II
- LeetCode(113)Path Sum II
- LeetCode: Path Sum II [113]
- [leetcode 113] Path Sum II
- [LeetCode 113]Path Sum II
- leetcode || 113、Path Sum II
- Leetcode[113]-Path Sum II
- Path Sum II - LeetCode 113
- LeetCode(113) Path Sum II
- Leetcode #113 Path Sum II
- leetcode 113: Path Sum II
- LeetCode 113: Path Sum II
- LeetCode 113 Path Sum II
- LeetCode 113:Path Sum II
- LeetCode 113 Path Sum II
- leetcode 113 Path Sum II
- Leetcode 113 Path Sum II
- leetcode 113 Path Sum II
- linux3.10.65 DMA缓冲区分配失败
- ARC Semantic issue:No visiable @interface for xxx declares the selector yyy 与arc semantic issue
- 《分布式JAVA应用 基础与实践》 第六章 构建高可用的系统
- Cassandra中的各种策略
- 一般用sudo 执行的需要授权
- [Leetcode] #113 Path Sum II
- 博客起步!
- 分数求和保留两位小数
- iOS 编码注意事项及技巧
- Android 打造炫目的圆形菜单 秒秒钟高仿建行圆形菜单
- FMDB数据库
- 解决HttpServletResponse输出的中文乱码问题
- Cassandra 数据模型
- springMVC--处理器适配器