The path summation finds all paths to the leaf node

The path summation finds all paths to the leaf node

Give you the root node root of the binary tree and an integer target and targetSum, and find all the paths whose sum of paths from the root node to the leaf nodes is equal to the given target sum.

Leaf nodes are nodes that have no child nodes.

class Solution {
    
    
    List<List<Integer>> arrays = new ArrayList<List<Integer>>();
    public List<List<Integer>> pathSum(TreeNode root, int targetSum) {
    
    
        if(root==null){
    
    
            return arrays;
        }
        ArrayList<Integer> array = new ArrayList<Integer>();
        helpSum(array, root, targetSum);
        return arrays;
    }
    public void helpSum(ArrayList<Integer> array, TreeNode root, int target){
    
    
        if(root==null){
    
    
            return;
        }
        array.add(root.val);
        if(root.left==null&&root.right==null&&target==root.val){
    
    
            arrays.add(new ArrayList<Integer>(array));
        }
        helpSum(array, root.left, target-root.val);
        helpSum(array, root.right, target-root.val);
        array.remove(array.size()-1);
    }
}

Guess you like

Origin blog.csdn.net/xiaomagezuishuai/article/details/114435397