[CareerCup] 4.9 All Paths Sum 所有路径和
4.9 You are given a binary tree in which each node contains a value. Design an algorithm to print all paths which sum to a given value. The path does not need to start or end at the root or a leaf.
这道题给我们一个二叉树,让我们找出所有的路径,其和为给定的值,而且说了路径不必起始于根,终止于叶节点,但必须是向下的一条路径。LeetCode中相似的题有Path Sum 二叉树的路径和 和 Path Sum II 二叉树路径之和之二。但是那题要找的是起始于根,终止于叶节点的路径,而这题是找出所有的路径。所以要稍稍复杂一些。这题的解题思路是先求出给定二叉树的深度,关于求二叉树的深度可以参见我之前的博客Maximum Depth of Binary Tree 二叉树的最大深度。然后我们建立一个大小为树的最大深度的一维向量,用来存每一层路径上的值。然后从第一层开始递归,对每一个节点,更新当前层的path,然后从此层向第一层遍历,将path各层值加起来,如果等于sum的话,就把这道路径打印或者保存起来,然后在对当前节点的左右子节点分别递归调用。时间复杂度为O(nlgn),空间复杂度为O(lgn),参见代码如下:
解法一:
class Solution {
public:
vector<vector<int> > pathSum(TreeNode *root, int sum) {
if (!root) return vector<vector<int> >();
int depth = getDepth(root);
vector<vector<int> > res;
vector<int> path(depth, INT_MIN);
pathSumDFS(root, sum, , path, res);
return res;
}
void pathSumDFS(TreeNode *root, int sum, int level, vector<int> &path, vector<vector<int> > &res) {
if (!root) return;
path[level] = root->val;
int t = ;
for (int i = level; i >= ; i--) {
t += path[i];
if (t == sum) {
savePath(path, i, level, res);
}
}
pathSumDFS(root->left, sum, level + , path, res);
pathSumDFS(root->right, sum, level + , path, res);
path[level] = INT_MIN;
}
void savePath(vector<int> &path, int start, int end, vector<vector<int> > &res) {
vector<int> out;
for (int i = start; i <= end; ++i) {
out.push_back(path[i]);
}
res.push_back(out);
}
int getDepth(TreeNode *root) {
if (!root) return ;
return + max(getDepth(root->left), getDepth(root->right));
}
};
然而书上的解法并不是最简洁的,下面这种方法是评论区的网友提出来的,感觉很简洁很好,赞一个~
解法二:
class Solution {
public:
vector<vector<int> > pathSum(TreeNode *root, int sum) {
if (!root) return {};
vector<vector<int>> res;
vector<int> path;
helper(root, sum, path, res);
return res;
}
void helper(TreeNode* node, int sum, vector<int>& path, vector<vector<int>>& res) {
if (!node) return;
path.push_back(node->val);
int curSum = ;
for (int i = path.size() - ; i >= ; --i) {
curSum += path[i];
if (curSum == sum) res.push_back(vector<int>(path.begin() + i, path.end()));
}
helper(node->left, sum, path, res);
helper(node->right, sum, path, res);
path.pop_back();
}
};
[CareerCup] 4.9 All Paths Sum 所有路径和的更多相关文章
- [LeetCode] 113. Path Sum II 路径和 II
Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given su ...
- [LeetCode] 437. Path Sum III 路径和 III
You are given a binary tree in which each node contains an integer value. Find the number of paths t ...
- Redundant Paths 分离的路径
Redundant Paths 分离的路径 题目描述 为了从F(1≤F≤5000)个草场中的一个走到另一个,贝茜和她的同伴们有时不得不路过一些她们讨厌的可怕的树.奶牛们已经厌倦了被迫走某一条路,所以她 ...
- 【LeetCode】113. Path Sum II 路径总和 II 解题报告(Python)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.me/ 文章目录 题目描述 题目大意 解题方法 BFS DFS 日期 题目地址:https:// ...
- 剑指Offer23 二叉树中和为sum的路径
/************************************************************************* > File Name: 23_FindPa ...
- BZOJ 1718: [Usaco2006 Jan] Redundant Paths 分离的路径( tarjan )
tarjan求边双连通分量, 然后就是一棵树了, 可以各种乱搞... ----------------------------------------------------------------- ...
- 【LeetCode-面试算法经典-Java实现】【062-Unique Paths(唯一路径)】
[062-Unique Paths(唯一路径)] [LeetCode-面试算法经典-Java实现][全部题目文件夹索引] 原题 A robot is located at the top-left c ...
- 【bzoj1718】Redundant Paths 分离的路径
1718: [Usaco2006 Jan] Redundant Paths 分离的路径 Time Limit: 5 Sec Memory Limit: 64 MBSubmit: 964 Solve ...
- [Usaco2006 Jan] Redundant Paths 分离的路径
1718: [Usaco2006 Jan] Redundant Paths 分离的路径 Time Limit: 5 Sec Memory Limit: 64 MBSubmit: 1132 Solv ...
随机推荐
- LeetCode 6 ZigZag Conversion(规律)
题目来源:https://leetcode.com/problems/zigzag-conversion/ The string "PAYPALISHIRING" is writt ...
- javascript中的 cookie对象
Cookie 对象 是一种以文件(Cookie文件)的形式保存在客户端硬盘的Cookies文件夹中的数据信息(Cookie数据).Cookie文件夹中的用户数据信息(Cookie数据).Cookie文 ...
- 2013MPD上海6.23 PM 光耀:读心术,用户心理的产品之道
创新的前提是:制度与组织的创新!!!!!!!!!!!!!! 光耀:腾讯互联网业务产品经理(腾讯公司互联网业务系统产品经理.在电子商务.社会化媒体等方面有深入研究.参与腾讯多个重要项目产品工作) 什么是 ...
- Remote Desktop Connection Manager (RDCMan) 介绍
Remote Desktop Connection Manager介绍 Remote Desktop Connection Manager (RDCMan) 是微软Windows Live体验团队的主 ...
- 《SQL Server企业级平台管理实践》读书笔记——SQL Server数据库文件分配方式
1.文件分配方式以及文件空间检查方法 最常用的检查数据文件和表大小的命令就是:sp_spaceused 此命令有三个缺陷:1.无法直观的看出每个数据文件和日志文件的使用情况.2.这个存储过程依赖SQL ...
- 【mysql】添加对emoji的支持
1.简介 涉及无线相关的 MySQL 数据库建议都提前采用 utf8mb4 字符集,避免 emoji 表情符号带来的问题 MySQL Server > 5.5.3 2.配置+升级 当前配置 m ...
- oracle缓存池使用解析
oracle有三种类型的缓存池,分别是default,keep和recycle.默认情况下只会使用default缓存池,另外两种需要额外配置. keep缓存池相当于是一直很热的default缓存池,缓 ...
- oracle归档日志写满错误解决方法
最近一年,手头上负责的项目要部署到很多个地方,由于项目组里没有人对oracle比较熟悉,只能给自己增加一个DBA的角色了.由于短时间内要部署很多单位,备份策略没有设置好,结果过了一个月,用户报告程序开 ...
- Linux学习之二——档案与目录的属性和权限
一.属性和权限的基本概念 Linux一般将档案可存取的身份分为三个类别,分别是 owner/group/others,这三种身份各有 read/write/execute 等权限. 所有的系统上的账号 ...
- javascript原型Prototype
在javaScript创建对象一文中提到过:用构造函数创建对象存在一个问题即同一构造函数的不同实例的相同方法是不一样的,所以我们用原型把构造函数中公共的属性和方法提取出来进行封装,达到让所有实例共享的 ...