Title description
Given a binary tree and a value \sum sum, please find the path where the sum of the node values from the root node to the leaf node is equal to \sum sum,
for example:
Given the following binary tree, \sum=22 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]]
Code implementation :
import java.util.*;
/*
* public class TreeNode {
* int val = 0;
* TreeNode left = null;
* TreeNode right = null;
* }
*/
public class Solution {
/**
*
* @param root TreeNode类
* @param sum int整型
* @return int整型ArrayList<ArrayList<>>
*/
private ArrayList<ArrayList<Integer>> listAll = new ArrayList<>();
private ArrayList<Integer> list = new ArrayList<>();
public ArrayList<ArrayList<Integer>> pathSum(TreeNode root, int target) {
if (root == null) {
return listAll;
}
list.add(root.val);
target -= root.val;
if (target == 0 && root.left == null && root.right == null) {
listAll.add(new ArrayList<>(list));
}
pathSum(root.left, target);
pathSum(root.right, target);
// 回退
list.remove(list.size() - 1);
return listAll;
}
}