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. yii2.0的学习之旅(二)

    前言:上一次我们简单认识了一下yii2.0安装,模型基本(增,删,改,查)操作 一.前后台数据交互 *如果你觉得默认的top样式太丑,可以这样关掉* *底部也可以这样关掉* (1)mvc合作操作数据 ...

  2. dedecms5.7的获取本文章的TAG

    tag调用标签如下: {dede:tag row='10' getall='1' sort='month'} <li><a href='[field:link/]'>[fiel ...

  3. JavaScript AJAX PHP

    AJAX PHP示例 AJAX用于创建更多交互式应用程序. 以下示例演示了当用户在输入字段中键入字符时,网页如何与Web服务器通信: <!DOCTYPE html> <html> ...

  4. shiro加密算法

    第一节的时候我介绍过,shiro有很多加密算法,如md5和sha,而且还支持加盐,使得密码的解析变得更有难度,更好的保障了数据的安全性. 这里我们要介绍的是md5算法,因为比较常用.首先我们来看看md ...

  5. Ubuntu19.04安装常用软件

    安装Indicator Stickynotes 桌面便签小工具sudo add-apt-repository ppa:umang/indicator-stickynotessudo apt-get u ...

  6. NLP中的预训练语言模型(四)—— 小型化bert(DistillBert, ALBERT, TINYBERT)

    bert之类的预训练模型在NLP各项任务上取得的效果是显著的,但是因为bert的模型参数多,推断速度慢等原因,导致bert在工业界上的应用很难普及,针对预训练模型做模型压缩是促进其在工业界应用的关键, ...

  7. Rust中的错误处理

    Result & Panic 这次讲得详细,从错误的来历及简写过程, 都写明白了, 先浅,再深,先深,再浅, 反复之, 学习王道~ use std::fs::File; //use std:: ...

  8. 初识v4l2(四)-------v4l2_open、v4l2_read、v4l2_write浅析

    原文:https://blog.csdn.net/leesagacious/article/details/49995729 1.app:     open("/dev/video0&quo ...

  9. Java虚拟机所管理的内存,包含的运行时数据区域?

    运行时数据区域 线程私有(随用户线程的启动和结束而建立和销毁)或所有线程共享(随虚拟机进程的启动而存在) 抛出的异常 备注 程序计数器(Program Counter Register) 线程私有 唯 ...

  10. Android开发环境搭建(个人环境非通用)

    1.安装andorid studio 2.连接模拟器,AMD处理器为无法使用AVD manager ,所以连接第三方的Genymotion模拟器,设置中安装Genymotion插件,重启即可(Geny ...