美文网首页
[刷题防痴呆] 0113 - 路径总和 II (Path Sum

[刷题防痴呆] 0113 - 路径总和 II (Path Sum

作者: 西出玉门东望长安 | 来源:发表于2022-02-17 00:19 被阅读0次

题目地址

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

题目描述

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 sum.

Note: A leaf is a node with no children.

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

思路

dfs. 恢复现场.

关键点

  • 注意, 即使是加入到res里的path也需要恢复现场, 因为后续可能继续dfs.

代码

  • 语言支持:Java
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public List<List<Integer>> pathSum(TreeNode root, int sum) {
        List<Integer> path = new ArrayList<>();
        List<List<Integer>> result = new ArrayList<>();
        
        helper(root, sum, path, result);
        
        return result;
    }
    
    private void helper(TreeNode root, int sum, List<Integer> path, 
                         List<List<Integer>> result) {
        if (root == null) {
            return;
        }
        path.add(root.val);
        
        if (sum == root.val && root.left == null && root.right == null) {
            result.add(new ArrayList<>(path));
        } else {
            helper(root.left, sum - root.val, path, result);
            helper(root.right, sum - root.val, path, result);
        }
        
        path.remove(path.size() - 1);
    }
}

相关文章

网友评论

      本文标题:[刷题防痴呆] 0113 - 路径总和 II (Path Sum

      本文链接:https://www.haomeiwen.com/subject/vasohrtx.html