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. 关于Block Formatting Context--BFC和IE的hasLayout

    转文请标明 --- 出处:穆乙 http://www.cnblogs.com/pigtail/ 一.BFC是什么? BFC(Block Formatting Context)直译为"块级格式 ...

  2. Effective Java 24 Eliminate unchecked warnings

    Note Eliminate every unchecked warning that you can. Set<Lark> exaltation = new HashSet(); The ...

  3. Python基本数据结构-字典-创建/访问/基本操作/格式化输出

  4. Java读写txt文件

    1.Java读取txt文件 1.1.使用FileInputStream: public static String readFile(File file, String charset){ //设置默 ...

  5. java工程中的相关路径

    一.路径 绝对路径: 指的是文件在系统中的真实路径(物理路径). 相对路径: 指的是文件相对某个目录的相对路径. 对于java application 工程来说,当编写完一个类之后,class文件会编 ...

  6. 常用vi编辑命令

    在自己的博客里存起来,这么多全记住确实有点难,时不时的翻一翻到是可以的. 摘自:http://www.cnblogs.com/junw_china/articles/1708967.html 光标控制 ...

  7. 字符串长度函数strlen()

    如下是我的测试文件: #include <stdio.h> #include <stdlib.h> #include <string.h> int main() { ...

  8. openPOWERLINK开源POWERLINK协议栈说明文档中文非官方翻译

    GitBook分享,翻译进行中:https://winshton.gitbooks.io/openpowerlink-stack-cn/content/

  9. Linux (二) vi

    1  步骤 1)  vi  test.txt 进入一般模式 2)   i    进入编辑模式,输入内容 3)  Esc 回到一般模式 4)  :wq 存储后退出 2  编辑模式 [i] 光标处插入, ...

  10. HDU 3333 Turing Tree --树状数组+离线处理

    题意:统计一段序列[L,R]的和,重复元素只算一次. 解法:容易看出在线做很难处理重复的情况,干脆全部讲查询读进来,然后将查询根据右端点排个序,然后离散化数据以后就可以操作了. 每次读入一个数,如果这 ...