[LeetCode] 113. Path Sum II

Given the root of a binary tree and an integer targetSum, return all root-to-leaf paths where the sum of the node values in the path equals targetSum. Each path should be returned as a list of the node values, not node references. A root-to-leaf path is a path starting from the root and ending at any leaf node. A leaf is a node with no children.
Example1:

Input: root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22
Output: [[5,4,11,2],[5,8,4,5]]
Explanation: There are two paths whose sum equals targetSum:
5 + 4 + 11 + 2 = 22
5 + 8 + 4 + 5 = 22

Example2:

Input: root = [1,2,3], targetSum = 5
Output: []

Example3:

Input: root = [1,2], targetSum = 0
Output: []

Constraints:

  • The number of nodes in the tree is in the range [0, 5000].
  • -1000 <= Node.val <= 1000
  • -1000 <= targetSum <= 1000

这道题其实和Path Sum很相似。不同的是需要把path给记下来。其实知道题就是dfs(深度优先搜索), 每次都要到叶子结点满足条件才算是真的满足条件。
注意:

  • DFS中每次回到前面的结点都要把之前加入的那个值去掉,不然的话path就不对了
  • 把path加到最后返回的list的时候,需要做一次深度copy,不然的话path改变,结果的list也跟着改变。
  • 深度copy的时候怎么写
/**
 * 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 targetSum) {
        List<List<Integer>> rst = new ArrayList<>();
        if (root == null) {
            return rst;
        }
        List<Integer> path = new ArrayList<>();
        process(root, targetSum, rst, path);
        return rst;
    }
    
    private void process(TreeNode root, int targetSum,
                         List<List<Integer>> rst, List<Integer> path) {
        if (root == null) {
            return;
        }
        path.add(root.val);
        if (root.left == null && root.right == null && root.val == targetSum) {
            rst.add(new ArrayList(path));
        }
        
        process(root.left, targetSum - root.val, rst, path);
        process(root.right, targetSum - root.val, rst, path);
        
        path.remove(path.size() - 1);
    }
    
}                        
上一篇:2022-1-9二叉树day3


下一篇:[LeetCode] 98. Validate Binary Search Tree