leetcode113. Path sum II
来源:互联网 发布:寻觅直播软件 编辑:程序博客网 时间:2024/06/10 00:41
这道题是path sum I的升级版,通过这道题我发觉我竟然忘了树的一个重要定义。所以在这做一个记录:
题目描述如下:
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]
]
即给了一个总的sum值,要求找到所有从根结点到叶子结点路径和等于sum值的路径。这一点要复习一下什么是叶子结点,这对求和很重要。叶子结点就是没有子结点的结点,在二叉树中没有右节点也没有左结点,知道了这个,方法就简单了,递归深度搜索遍历树,找到符合条件的路径:
这是我的方法:
class Solution {private: vector<vector<int>> res; void findpath(TreeNode* root,int sum,vector<int> num) { if(!root) return; num.push_back(root->val); if((!root->left) && (!root->right) && sum==root->val) { res.push_back(num); return; } findpath(root->left,sum-(root->val),num); findpath(root->right,sum-(root->val),num); }public: vector<vector<int>> pathSum(TreeNode* root, int sum) { vector<int> temp; findpath(root,sum,temp); return this->res; }};
这里的递归函数,我直接传入了vector num这个形参,而没有用引用是想着避免num要手动进栈出栈的操作。但是确实在递归的使用用vector这样的形参太浪费时间和空间了,因为每次传对象的形参的时候都要调用拷贝构造函数,递归的层数一多就会很棘手,所以,这里参考了一下最高赞答案,还是用了引用的形式:
class Solution {private: void findpath(TreeNode* root,int sum,vector<vector<int>> &paths,vector<int> &path) { if(!root) return; path.push_back(root->val); if((!root->left) && (!root->right) && sum==root->val) { paths.push_back(path); } findpath(root->left,sum-(root->val),paths,path); findpath(root->right,sum-(root->val),paths,path); path.pop_back(); }public: vector<vector<int>> pathSum(TreeNode* root, int sum) { vector<vector<int>> paths; vector<int> path; findpath(root,sum,paths,path); return paths; }};
阅读全文
0 0
- LeetCode113 Path Sum II
- Leetcode113. Path Sum II
- LeetCode113:Path Sum II
- LeetCode113. Path Sum II
- LeetCode113. Path Sum II
- leetcode113~Path Sum II
- LeetCode113 Path Sum II
- leetcode113. Path Sum II
- leetcode113. Path sum II
- LeetCode113. Path Sum II
- LeetCode113—Path Sum II
- LeetCode113. Path Sum II(Medium)
- LeetCode: Path Sum II
- LeetCode Path Sum II
- [Leetcode] Path Sum II
- LeetCode: Path Sum II
- Path Sum II
- [LeetCode] Path Sum II
- 深度学习中的正则化方法
- 数学基础—ML
- hibernate框架
- POJ2947:Widget Factory(高斯消元,解模线性方程)
- Struts2配置struts.xml文件
- leetcode113. Path sum II
- Pycharm使用技巧:File Encoding(修改文件编码)
- Python3-end关键字
- CentOS7安装mysql5.7.19的手顺,步骤(非常详细)
- 不要好了Bug忘了疼
- UBOOT源码详细分析之主Makefile
- OpenCV2编程手册笔记之 7.6计算连通区域的形状描述符
- 装完Anaconda后和系统自带Python共存
- 精确率、召回率、F1 值、ROC、AUC 各自的优缺点