leetcode 113 —— Path Sum II
来源:互联网 发布:淘宝网店管理制度 编辑:程序博客网 时间:2024/05/16 13:38
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]]
思路 :回溯法,事实表明,使用引用的路径能显著提高运行速度
class Solution {public:vector<vector<int>> pathSum(TreeNode* root, int sum) {vector<vector<int>> res;vector<int> path;dfs(root, 0, sum, path, res);return res;}void dfs(TreeNode* root, int cnt, int sum, vector<int>& path, vector<vector<int>> &res){if (!root)return;if (!root->left&&!root->right){if (cnt + root->val == sum){path.push_back(root->val);res.push_back(path);path.pop_back();return;}}path.push_back(root->val);dfs(root->left, cnt + root->val, sum, path, res);dfs(root->right, cnt + root->val, sum, path, res);path.pop_back();return; //其实不加也可以,void函数执行完后自动返回上级}};
0 0
- leetcode 113 —— Path Sum II
- LeetCode——Path Sum II
- leetcode——Path Sum II
- LeetCode题解——Path Sum II
- leetcode——113——Path Sum II
- 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
- 使用系统自带的ContentProvider查询联系人
- springmvc配置
- 我的世界史蒂夫——熊孩子版
- 线段树之POJ2528 Mayor's posters
- 解禁 MAVEN “Plugin execution not covered by lifecycle configuration” 问题
- leetcode 113 —— Path Sum II
- Axis2插件的安装以及代码生成
- Apache 模块介绍
- 多线程理论
- HDOJ 1686 Oulipo (KMP)
- A + B高精度
- Cacti的配置详解(一)——使用rrdtool绘图
- jquery学习
- fgetc,feof