LeetCode刷题(C++)——Path Sum II(Medium)
来源:互联网 发布:2017淘宝评价计分规则 编辑:程序博客网 时间:2024/06/05 05:56
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]]
/** * 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>> path;if (root == NULL)return path;int cursum = 0;vector<int> onepath;dfs(root, sum, cursum, onepath, path);return path;}void dfs(TreeNode* root, int sum, int cursum, vector<int> onepath, vector<vector<int>>& path){cursum += root->val;onepath.push_back(root->val);bool isLeaf = (root->left == NULL) && (root->right == NULL);if (cursum == sum&&isLeaf)path.push_back(onepath);if (root->left != NULL)dfs(root->left, sum, cursum, onepath, path);if (root->right != NULL)dfs(root->right, sum, cursum, onepath, path);onepath.pop_back(); }};
0 0
- LeetCode刷题(C++)——Path Sum II(Medium)
- LeetCode刷题(C++)——Minimum Path Sum(Medium)
- LeetCode刷题(C++)——3Sum(Medium)
- LeetCode刷题(C++)——4Sum(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)
- Path Sum II(medium)
- LeetCode刷题(C++)——Path Sum(Easy)
- [leetcode] 040. Combination Sum II (Medium) (C++)
- LeetCode刷题(C++)——3Sum Closest(Medium)
- LeetCode刷题(C++)——Remove Duplicates from Sorted List II(Medium)
- LeetCode刷题(C++)——Remove Duplicates from Sorted Array II(Medium)
- LeetCode刷题(C++)——Linked List Cycle II(Medium)
- LeetCode113. Path Sum II(Medium)
- LeetCode——Path Sum II
- leetcode——Path Sum II
- Docker网络(一)---------原生支持
- 心得
- 设计模式之代理模式
- c++短路求值
- 欢迎使用CSDN-markdown编辑器
- LeetCode刷题(C++)——Path Sum II(Medium)
- 电子书及阅读器Demo
- AppCompatActivity如何去掉标题栏
- gdb调试命令的使用及总结
- Linux下的atexit函数
- 详解SpringMVC请求的时候是如何找到正确的Controller
- BZOJ2186]沙拉公主的困惑(求1-N!中与M!互质的数的个数)
- HDOJ 2003 求绝对值
- 科猫首页html编写