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. mysql集群之MYSQL CLUSTER

    1. 参考文档 http://xuwensong.elastos.org/2014/01/13/ubuntu-%E4%B8%8Bmysql-cluster%E5%AE%89%E8%A3%85%E5%9 ...

  2. 设计模式 --- 单例模式(Singleton)

    一.概念 单例模式是一种常用的软件设计模式.在它的核心结构中只包含一个被称为单例的特殊类.通过单例模式可以保证系统中一个类只有一个实例而且该实例易于外界访问,从而方便对实例个数的控制并节约系统资源.如 ...

  3. OracleGateway11gR2访问异构数据库(MSSQL)配置文档(转)

    1.前提条件 1. 准备工作 软件名称 操作系统 IP地址 端口 用户 密码 版本 状态 Oracle数据库 Windows localhost 1521 scott scott win32 Orac ...

  4. subline 快捷键

    subline 快捷键  安装 pretty css  html  后1,CTRl+ shift +H 格式化代码

  5. Eclipse中使用Git-让版本管理更简单

    详细步骤: 第一部分  GIT介绍 (1)GIT往世今生 2005年开发Samba的Andrew试图破解BitKeeper(一款商业的版本控制系统)的协议(这么干的其实也不只他一个),被BitMove ...

  6. ZOJ 3865 Superbot(优先队列--模板)

    题目链接:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemId=5477 主要思路:1.从一个点(cur)到它相邻的点(next),所需 ...

  7. 将text 文件转为List

    Integer 类型 ArrayList<Integer> Mlist = new ArrayList<Integer>(); Scanner scM = new Scanne ...

  8. 有用的MySQL语句

    摘自onefish资料库 1. 计算年数你想通过生日来计算这个人有几岁了. SELECT DATE_FORMAT(FROM_DAYS(TO_DAYS(now()) - TO_DAYS(@dateofb ...

  9. Same Tree

    Given two binary trees, write a function to check if they are equal or not. Two binary trees are con ...

  10. nopcommerce之权限模块

    这篇文章简单介绍一下nopcommerce的权限模块,nopcommerce里面的权限设计相对比较简单,主要针对后台的action和前台的是否显示(比如产品.品牌等),虽然简单但是应付一般的项目应该没 ...