LeetCode (Path Sum II)
来源:互联网 发布:淘宝二手车市场 编辑:程序博客网 时间:2024/06/10 01:23
Problem:
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:/** * 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>> ans; if(!root) return ans; if(!root->right && !root->left){ if(sum == root->val) return {{root->val}}; else return ans; } vector<vector<int>> right = pathSum(root->right, sum - root->val); vector<vector<int>> left = pathSum(root->left, sum - root->val); for(int i = 0; i < left.size(); i++){ vector<int> tmp = left[i]; tmp.insert(tmp.begin(), root->val); ans.push_back(tmp); } for(int i = 0; i < right.size(); i++){ vector<int> tmp = right[i]; tmp.insert(tmp.begin(), root->val); ans.push_back(tmp); } return ans; }};
阅读全文
0 0
- 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
- LeetCode | Path Sum II
- 【leetcode】Path Sum II
- [LeetCode] Path Sum II
- Dajngo19-缓存与静态页面
- STM32 4字节对齐问题
- 23种设计模式理解
- 参数解析
- Android全局捕获crash并保存日志到本地
- LeetCode (Path Sum II)
- ASP.NET小结
- 启用开发者模式--微信公众平台开发(三)
- Java架构师之路
- TensorBoard
- 学习 FPGA 经验与书籍
- NVIDIA Jetson TX2 安装nano编辑器
- Django20-安全与国际化
- 三元组运算加法和乘法