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 所有路径和的更多相关文章

  1. [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 ...

  2. [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 ...

  3. Redundant Paths 分离的路径

    Redundant Paths 分离的路径 题目描述 为了从F(1≤F≤5000)个草场中的一个走到另一个,贝茜和她的同伴们有时不得不路过一些她们讨厌的可怕的树.奶牛们已经厌倦了被迫走某一条路,所以她 ...

  4. 【LeetCode】113. Path Sum II 路径总和 II 解题报告(Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.me/ 文章目录 题目描述 题目大意 解题方法 BFS DFS 日期 题目地址:https:// ...

  5. 剑指Offer23 二叉树中和为sum的路径

    /************************************************************************* > File Name: 23_FindPa ...

  6. BZOJ 1718: [Usaco2006 Jan] Redundant Paths 分离的路径( tarjan )

    tarjan求边双连通分量, 然后就是一棵树了, 可以各种乱搞... ----------------------------------------------------------------- ...

  7. 【LeetCode-面试算法经典-Java实现】【062-Unique Paths(唯一路径)】

    [062-Unique Paths(唯一路径)] [LeetCode-面试算法经典-Java实现][全部题目文件夹索引] 原题 A robot is located at the top-left c ...

  8. 【bzoj1718】Redundant Paths 分离的路径

    1718: [Usaco2006 Jan] Redundant Paths 分离的路径 Time Limit: 5 Sec  Memory Limit: 64 MBSubmit: 964  Solve ...

  9. [Usaco2006 Jan] Redundant Paths 分离的路径

    1718: [Usaco2006 Jan] Redundant Paths 分离的路径 Time Limit: 5 Sec  Memory Limit: 64 MBSubmit: 1132  Solv ...

随机推荐

  1. chrome浏览器font-size<12px无效解决办法

    当样式设定font-size<12px时,chrome浏览器里字体显示仍为12px:如font-size:11px; 但是chrome还是12px的大小,很不听话. 今天我就遇到了这样的问题?网 ...

  2. 烂泥:ubuntu安装KVM虚拟机管理virt-manager

    本文由秀依林枫提供友情赞助,首发于烂泥行天下. 打算学习KVM的图形界面管理器virt-manager,但是virt-manager只有linux系统的,没有windows下的.所以只能使用linux ...

  3. JS高级程序设计2nd部分知识要点3

    对象转换方法:1> toLocaleString(),2> toString(),ValueOf()方法会返回相同的值 栈方法是 LIFO (后进先出)的数据结构 -push ,pop 方 ...

  4. python 练习多级菜单思路

    只写了一个zj的三级菜单,后面的功能没写 #-*- coding :utf-8 -*- print """ 你可以输入省份然后根据市县输入 ""&qu ...

  5. zip文件jQuery工作地点选择城市代码

    效果 地址下载:http://download.csdn.net/detail/xiaoliu123586/9201925 2.效果 源码:http://download.csdn.net/detai ...

  6. Windows Live Writer离线编写博客

    WLW最新版本为2012,官网下载 Windows Live Writer配置步骤 使用Windows Live Writer 2012和Office Word 2013 发布文章到博客园全面总结 L ...

  7. scons使用

    1.概述 scons是一个Python写的自动化构建工具,和GNU make相比优点明显:    A.移植性:python能运行的地方,就能运行scons    B. 扩展性:理论上scons只是提供 ...

  8. MPP 架构数据库

    Greenplum是一种基于postgresql的分布式数据库.其采用shared nothing架构(MPP),主机,操作系统,内存,存储都是自我控制的,不存在共享.也就是每个节点都是一个单独的数据 ...

  9. uva 699 the falling leaves——yhx

    aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAA3QAAAMsCAIAAACTL3d2AAAgAElEQVR4nOx9y7GuPA4tKRADk/92T8 ...

  10. 【Android UI设计与开发】7.底部菜单栏(四)PopupWindow 实现显示仿腾讯新闻底部弹出菜单

    前一篇文章中有用到 PopupWindow 来实现弹窗的功能.简单介绍以下吧. 官方文档是这样解释的:这就是一个弹出窗口,可以用来显示一个任意视图.出现的弹出窗口是一个浮动容器的当前活动. 1.首先来 ...