LeetCode[Tree]: Path Sum II
来源:互联网 发布:信阳师范学院网络教学 编辑:程序博客网 时间:2024/05/01 11:25
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,
return
这个题目适合用递归来解,我的C++代码实现如下:
class Solution {public: vector<vector<int> > pathSum(TreeNode *root, int sum) { vector<vector<int> > paths; vector<int> curr_path; if (!root) return paths; find(root, sum, paths, curr_path); return paths; }private: void find(TreeNode *root, int sum, vector<vector<int> > &paths, vector<int> &curr_path) { curr_path.push_back(root->val); if (root->left == nullptr && root->right == nullptr) if (root->val == sum) paths.push_back(curr_path); if (root->left) { find(root->left, sum - root->val, paths, curr_path); curr_path.pop_back(); } if (root->right) { find(root->right, sum - root->val, paths, curr_path); curr_path.pop_back(); } }};
时间性能如下图所示:
0 0
- **(leetcode) (tree) Path Sum II
- LeetCode[Tree]: Path Sum II
- [leetcode][tree][dfs] Path Sum II
- LeetCode: Path Sum II
- LeetCode Path Sum II
- [Leetcode] Path Sum II
- LeetCode: Path Sum II
- [LeetCode] Path Sum II
- 【leetcode】Path Sum II
- [LeetCode]Path Sum II
- [Leetcode]Path Sum II
- [leetcode]Path Sum II
- Leetcode: Path Sum II
- LeetCode-Path Sum II
- [leetcode] Path Sum II
- LeetCode - Path Sum II
- [LeetCode] Path Sum II
- Leetcode Path Sum II
- 11-1. 通讯录的录入与显示(10)
- hdu 1078 记忆化搜索
- Tsinsen 清橙 A1015. 杨辉三角形 (循环)
- JDK 源码学习之String
- USACO4.3.3 Letter Game (lgame)
- LeetCode[Tree]: Path Sum II
- jvm 日志和参数的理解
- API开发第一篇:关于session的APP服务端API开发
- [Gym100016D] Group Stage
- java线程暂停与继续
- Qt核心剖析: moc
- hdu 1166 敌兵布阵 单点更新模板
- hdu 1555 How many days?
- 【BZOJ】【P1018】【SHOI2008】【堵塞的交通traffic】【题解】【线段树】