【Leetcode】113. 路径总和II

题目

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

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

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

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

返回:递归

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

题解

这道题目是上一道的延伸,可是须要记录下路径,返回回去。这就是一个典型的backtrack的题目了。咱们用迭代的方式须要记录中间的路径状态,稍显复杂,因此咱们想用递归的方式来解,先探索左子树,而后探索右子树。若是都探索完以后,右知足的就加入到最终结果中。rem

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);
    }
}

热门阅读

Leetcode名企之路
手撕代码QQ群:805423079, 群密码:1024get

相关文章
相关标签/搜索