Java finds the path where the sum of the node values from the root node to the leaf node is equal to sum

Title description

Given a binary tree and a value sum, please find the path where the sum of the node values ​​from the root node to the leaf node is equal to sum,
for example:
Given the following binary tree, sum=22,

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

Example 1

enter

{1,2},1

return value

[]

Example 2

enter

{1,2},3

return value

[[1,2]]

 

import java.util.*;

/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 * }
 */

public class Solution {
    ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
    ArrayList<Integer> path = new ArrayList();
    
    /**
     * 
     * @param root TreeNode类 
     * @param sum int整型 
     * @return int整型ArrayList<ArrayList<>>
     */
    public ArrayList<ArrayList<Integer>> pathSum (TreeNode root, int sum) {
        preTree(root,sum);
        return result;
    }
    
    public void preTree(TreeNode root,int sum){
        
        if(root == null){
            return;
        }
        
        if(root.left == null && root.right == null && sum - root.val == 0){
            path.add(root.val);
            result.add(new ArrayList<Integer>(path));
            path.remove(path.size()-1);
            return;
        }
        
        path.add(root.val);
        preTree(root.left,sum - root.val);
        preTree(root.right,sum - root.val);
        path.remove(path.size()-1);
    }
}

 

Guess you like

Origin blog.csdn.net/luzhensmart/article/details/112968165