首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【Leetcode】113. 路径总和II

【Leetcode】113. 路径总和II

作者头像
Leetcode名企之路
发布2019-04-25 14:34:40
3730
发布2019-04-25 14:34:40
举报
文章被收录于专栏:Leetcode名企之路Leetcode名企之路

题目

给定一个二叉树和一个目标和,找到所有从根节点到叶子节点路径总和等于给定目标和的路径。

说明: 叶子节点是指没有子节点的节点。

示例: 给定如下二叉树,以及目标和 sum = 22,

              5
             / \
            4   8
           /   / \
          11  13  4
         /  \    / \
        7    2  5   1

返回:

[
   [5,4,11,2],
   [5,8,4,5]
]

题解

这道题目是上一道的延伸,但是需要记录下路径,返回回去。这就是一个典型的backtrack的题目了。我们用迭代的方式需要记录中间的路径状态,稍显复杂,所以我们想用递归的方式来解,先探索左子树,然后探索右子树。如果都探索完之后,右满足的就加入到最终结果中。

public class Solution {
    public List<List<Integer>> pathSum(TreeNode root, int sum) {
        List<List<Integer>> res = new LinkedList<>();
        helper(root, sum, res, new LinkedList<>());
        return res;
    }

    public void helper(TreeNode root, int sum, List<List<Integer>> res, List<Integer> current) {
        if (root == null) {
            return;
        }
        current.add(root.val);
        if (root.left == null && root.right == null && sum == root.val) {
            // leaf node.
            res.add(new LinkedList<>(current));
            // back track.
            current.remove(current.size() - 1);
            return;
        }

        helper(root.left, sum - root.val, res, current);
        helper(root.right, sum - root.val, res, current);
        // back track.
        current.remove(current.size() - 1);
    }
}

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2019-04-14,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 Leetcode名企之路 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 题目
  • 题解
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档