Path Sum II :from LeetCode
来源:互联网 发布:php 获取地区 编辑:程序博客网 时间:2024/06/03 18:27
题目大意是:将二叉树中根到叶子的所有路径中节点值的和为给的的数字sum的路径返回,当然路径是以保存节点值而非指针的形式。
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]]解题思想可以沿用之前的path sum,只是这时我们需要存储从根到当前节点的路径上的所有点,只要一发现有符合条件的路径,保存就ok。
而这些点保存的形式很容易想到栈,我最开始单纯地想用VECTOR实现这个栈,当然结果是超时,代码如下,大家看看是不是有其他的问题:
class Solution {public: vector<vector<int>>result; vector<int> tmp; vector<vector<int> > pathSum(TreeNode *root, int sum) { int num; if(!root) return result; tmp.push_back(root->val); if(!root->right && !root->left && root->val==sum) { result.push_back(tmp); tmp.pop_back(); return result; }; if(!root->right && !root->left) { tmp.pop_back(); return result; } pathSum(root->left,sum-root->val); pathSum(root->right,sum-root->val); tmp.pop_back(); return result; }};
以为是这种方法不行,但在别人提醒下认为是数据结构不行。所以改用数组来实现栈,结果AC,代码如下
class Solution {public: vector<vector<int>>result; vector<int> tmp; int arry[10000]; int index; void dfs(TreeNode *root,int sum) { if(!root) return; arry[index++]=root->val; if(!root->right && !root->left && root->val==sum) { tmp.clear(); for(int i=0;i<index;i++) { tmp.push_back(arry[i]); } result.push_back(tmp); index--; return; }; if(!root->right && !root->left) { index--; return ; } dfs(root->left,sum-root->val); dfs(root->right,sum-root->val); index--; return ; } vector<vector<int> > pathSum(TreeNode *root, int sum) { if(!root) return result; index=0; dfs(root,sum); return result; }};
当然定义一个数组成员总是会让人觉得不快,因为面试官总会拿数据冗余或者空间复杂度来反问你。但在时空问题上总得有些取舍,但空间更优的方法总有,大家想想。
0 0
- Path Sum II :from LeetCode
- 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
- 【C语言】01 Hello World!
- 【C语言】02 函数
- 【C语言】03 基本数据类型
- 【C语言】04 printf和scanf函数
- 【C语言】05 基本语句和运算
- Path Sum II :from LeetCode
- 【C语言】06 数组
- 【C语言】07 字符串
- 【C语言】08 字符和字符串常…
- 【C语言】09 指针
- javaEE jsp 内置对象
- 【C语言】10 指向一维数组元…
- java netty之ByteToMessageDecoder
- 部分图表组件调研总结