其他分享
首页 > 其他分享> > [LeetCode] 113. Path Sum II

[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:

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

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

标签:TreeNode,val,Sum,II,targetSum,path,rst,Path,root
来源: https://www.cnblogs.com/codingEskimo/p/15780181.html