LeetCode113. Path Sum II(Medium)
来源:互联网 发布:linux 驱动与 win驱动 编辑:程序博客网 时间:2024/06/09 14:21
原题:https://leetcode.com/problems/path-sum-ii/description/
题目描述:
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]]
题解
和上一题解题思路一样。每次递归时,都将新的节点的值存入当前vector< int >中。如果当前节点是叶子节点且路径和等于sum,那就将当前vector< int >存入一个vector< vector< int >>变量中。因为每次递归vector< int >变量使用的都不是引用,所以每次调用递归时都会在函数中生成一个传递参数的副本,虽然浪费空间但是正好适合递归的做法。
代码:
/** * 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: void findPath(TreeNode* root, int sum, vector<int> v, vector<vector<int>>& vs) { if (!root) return; v.push_back(root->val); if (root->val == sum&&!root->left&&!root->right) vs.push_back(v); sum -= root->val; findPath(root->left, sum, v, vs); findPath(root->right, sum, v, vs); vector<int>().swap(v); } vector<vector<int>> pathSum(TreeNode* root, int sum) { vector<vector<int>> vs; findPath(root, sum, vector<int>(), vs); return vs; }};
114 / 114 test cases passed.
Status: Accepted
Runtime: 12 ms`
阅读全文
0 0
- LeetCode113. Path Sum II(Medium)
- LeetCode113 Path Sum II
- Leetcode113. Path Sum II
- LeetCode113:Path Sum II
- LeetCode113. Path Sum II
- LeetCode113. Path Sum II
- leetcode113~Path Sum II
- LeetCode113 Path Sum II
- leetcode113. Path Sum II
- leetcode113. Path sum II
- LeetCode113. Path Sum II
- LeetCode113—Path Sum II
- Path Sum II(medium)
- [Leetcode 113, Medium] Path sum II
- 【LeetCode】(113)Path Sum II(Medium)
- [leetcode]113. Path Sum II (medium)
- Leetcode 113. Path Sum II (Medium) (cpp)
- 64. Minimum Path Sum -Medium
- Vue之交互
- 原子变量CAS算法
- 洛谷【P2084】进制转换
- js实现图片的轮播
- SpringCloud(第 018 篇)Zuul 服务 API 网关微服务之代理与反向代理
- LeetCode113. Path Sum II(Medium)
- servlet实现验证码操作的代码
- leetcode Next Greater Element I 下一个更大的元素
- 第四周项目1
- 多线程面试题
- LeetCode- Find Bottom Left Tree Value
- Java进程突然消失
- eclipse 常用快捷键(一)
- Python学习:连接MySQL数据库