Path Sum II
来源:互联网 发布:淘宝显示在线人数插件 编辑:程序博客网 时间:2024/05/22 09:00
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]]
和上题类似,只是要遍历各种情况, 考虑到inorder的traverse,只需要push,然后遍历左右后pop就可以只维护一个vector, O(n)的空间, O(lgn)的效率,不过因为是递归,所以stack上还有空间。
/** * Definition for binary tree * 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> > res; vector<int> path; helper(root, sum, path, res); return res; } void helper(TreeNode* root, int sum, vector<int>& path, vector<vector<int> > & res){ if (root==0) return; path.push_back(root->val); if (!root->left && !root->right && root->val==sum){ res.push_back(path); } helper(root->left, sum-root->val, path,res); helper(root->right,sum-root->val, path,res); path.pop_back(); }};
0 0
- LeetCode: Path Sum II
- LeetCode Path Sum II
- [Leetcode] Path Sum II
- LeetCode: Path Sum II
- Path Sum II
- [LeetCode] Path Sum II
- 【leetcode】Path Sum II
- [113]Path Sum II
- Path Sum II
- Path Sum II
- [LeetCode]Path Sum II
- Path Sum II
- Path Sum II
- [Leetcode]Path Sum II
- [leetcode]Path Sum II
- Path Sum II
- Leetcode: Path Sum II
- Path Sum II
- 《特种兵之侦察兵》
- 判断字符串及其子串是否是包含回文字,如果包含输出长度。
- Longest Valid Parentheses
- iOS开发系列之常用自定义控件开发集—Android的Toast控件开发
- 欢迎使用CSDN-markdown编辑器
- Path Sum II
- 结构体和枚举
- 静态代码块
- Train Problem I(经典栈)
- Python标准库:内置函数sorted(iterable[, key][, reverse])
- [MFC] Edit Control单击全选后如何使后续的单击不全选?
- mutable关键字
- Hadoop源码导入Eclipse
- 《数据结构编程实验》 4.4.1Error Correction