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]
]

这道二叉树路径之和在之前那道题 Path Sum 的基础上又需要找出路径,但是基本思想都一样,还是需要用深度优先搜索 DFS,只不过数据结构相对复杂一点,需要用到二维的 vector,而且每当 DFS 搜索到新结点时,都要保存该结点。而且每当找出一条路径之后,都将这个保存为一维 vector 的路径保存到最终结果二维 vector 中。并且,每当 DFS 搜索到子结点,发现不是路径和时,返回上一个结点时,需要把该结点从一维 vector 中移除,参见代码如下:

解法一:

class Solution {
public:
vector<vector<int>> pathSum(TreeNode* root, int sum) {
vector<vector<int>> res;
vector<int> out;
helper(root, sum, out, res);
return res;
}
void helper(TreeNode* node, int sum, vector<int>& out, vector<vector<int>>& res) {
if (!node) return;
out.push_back(node->val);
if (sum == node->val && !node->left && !node->right) {
res.push_back(out);
}
helper(node->left, sum - node->val, out, res);
helper(node->right, sum - node->val, out, res);
out.pop_back();
}
};

下面这种方法是迭代的写法,用的是中序遍历的顺序,参考之前那道 Binary Tree Inorder Traversal,中序遍历本来是要用栈来辅助运算的,由于要取出路径上的结点值,所以用一个 vector 来代替 stack,首先利用 while 循环找到最左子结点,在找的过程中,把路径中的结点值都加起来,这时候取出 vector 中的尾元素,如果其左右子结点都不存在且当前累加值正好等于 sum 了,将这条路径取出来存入结果 res 中,下面的部分是和一般的迭代中序写法有所不同的地方,由于中序遍历的特点,遍历到当前结点的时候,是有两种情况的,有可能此时是从左子结点跳回来的,此时正要去右子结点,则当前的结点值还是算在路径中的;也有可能当前是从右子结点跳回来的,并且此时要跳回上一个结点去,此时就要减去当前结点值,因为其已经不属于路径中的结点了。为了区分这两种情况,这里使用一个额外指针 pre 来指向前一个结点,如果右子结点存在且不等于 pre,直接将指针移到右子结点,反之更新 pre 为 cur,cur 重置为空,val 减去当前结点,st 删掉最后一个结点,参见代码如下:

解法二:

class Solution {
public:
vector<vector<int>> pathSum(TreeNode* root, int sum) {
vector<vector<int>> res;
vector<TreeNode*> st;
TreeNode *cur = root, *pre = nullptr;
int val = ;
while (cur || !st.empty()) {
while (cur) {
st.push_back(cur);
val += cur->val;
cur = cur->left;
}
cur = st.back();
if (!cur->left && !cur->right && val == sum) {
vector<int> v;
for (auto &a : st) v.push_back(a->val);
res.push_back(v);
}
if (cur->right && cur->right != pre) {
cur = cur->right;
} else {
pre = cur;
val -= cur->val;
st.pop_back();
cur = nullptr;
}
}
return res;
}
};

Github 同步地址:

https://github.com/grandyang/leetcode/issues/113

类似题目:

Path Sum

Path Sum IV

Path Sum III

Binary Tree Maximum Path Sum

Sum Root to Leaf Numbers

Binary Tree Preorder Traversal

Binary Tree Paths

参考资料:

https://leetcode.com/problems/path-sum-ii/

https://leetcode.com/problems/path-sum-ii/discuss/36685/12ms-11-lines-C%2B%2B-Solution

https://leetcode.com/problems/path-sum-ii/discuss/36695/Java-Solution%3A-iterative-and-recursive

https://leetcode.com/problems/path-sum-ii/discuss/36683/DFS-with-one-LinkedList-accepted-java-solution

LeetCode All in One 题目讲解汇总(持续更新中...)

[LeetCode] 113. Path Sum II 二叉树路径之和之二的更多相关文章

  1. [LeetCode] Path Sum 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] 113. Path Sum II ☆☆☆(二叉树所有路径和等于给定的数)

    LeetCode 二叉树路径问题 Path SUM(①②③)总结 Path Sum II leetcode java 描述 Given a binary tree and a sum, find al ...

  3. LeetCode 112. Path Sum (二叉树路径之和)

    Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all ...

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

  5. LeetCode 113. Path Sum II路径总和 II (C++)

    题目: Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the give ...

  6. leetcode 113. Path Sum II (路径和) 解题思路和方法

    Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given su ...

  7. LeetCode 437. Path Sum III (路径之和之三)

    You are given a binary tree in which each node contains an integer value. Find the number of paths t ...

  8. [leetcode] 113. Path Sum II (Medium)

    原题链接 子母题 112 Path Sum 跟112多了一点就是保存路径 依然用dfs,多了两个vector保存路径 Runtime: 16 ms, faster than 16.09% of C++ ...

  9. [leetcode]113. Path Sum II路径和(返回路径)

    Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given su ...

随机推荐

  1. Docker安装使用以及mlsql的docker安装使用说明

    1.检查内核版本,必须是3.10及以上 uname -r 2.安装 yum -y install docker #1.启动   docker systemctl start docker #1.1.验 ...

  2. vue.js过度&动画、混入&插件

    1.vue  过度动画 1.过度 Vue 在插入.更新或者移除 DOM 时,提供多种不同方式的应用过渡效果.Vue 提供了内置的过渡封装组件,该组件用于包裹要实现过渡效果的组件. 语法格式: < ...

  3. mysql 8.0 group by 不对的问题

    select version(),@@sql_mode;SET sql_mode=(SELECT REPLACE(@@sql_mode,'ONLY_FULL_GROUP_BY',''));

  4. Spring Security OAuth2 Demo —— 客户端模式(ClientCredentials)

    前情回顾 前几节分享了OAuth2的流程与其它三种授权模式,这几种授权模式复杂程度由大至小:授权码模式 > 隐式授权模式 > 密码模式 > 客户端模式 本文要讲的是最后一种也是最简单 ...

  5. 【UOJ#62】【UR #5】怎样跑得更快(莫比乌斯反演)

    [UOJ#62][UR #5]怎样跑得更快(莫比乌斯反演) 题面 UOJ 题解 众所周知,\(lcm(i,j)=\frac{ij}{gcd(i,j)}\),于是原式就变成了: \[\sum_{j=1} ...

  6. C# 练习题 打印出100-999之间所有的”水仙花数”

    题目:打印出100-999之间所有的”水仙花数”,所谓”水仙花数”是指一个三位数,其各位数字立方和等于该数本身.例如:153是一个”水仙花数”,因为153=1的三次方+5的三次方+3的三次方.1.程序 ...

  7. LinuxShell——认识BATH这个Shell

    LinuxShell——认识BATH这个Shell 摘要:本文主要了解了Linux系统中的Shell,以及什么是BATH. 什么是Shell Shell是一个命令行解释器,它为用户提供了一个向Linu ...

  8. Python requests库的使用(一)

    requests库官方使用手册地址:http://www.python-requests.org/en/master/:中文使用手册地址:http://cn.python-requests.org/z ...

  9. 第一章 权限管理DEMO简介

    源代码GitHub:https://github.com/ZhaoRd/Zrd_0001_AuthorityManagement 1.系列介绍 工作已有五年之久,一直有想通过博客写点自己知道的,在博客 ...

  10. Python环境安装与基础语法(1)——计算机基础知识

    Python安装 pip #包管理工具 pip install #安装包 pip list #查看包 IPython #增强的python shell,自动补全,自动缩进,支持shell,增加了很多函 ...