package org.example.interview.practice; import java.util.ArrayList; /** * @author xianzhe.ma * @date 2021/7/12 * 求和为某个值的所哟路径 */ public class NC_8_BINARYTREE_SUMPATH { public static ArrayList<ArrayList<Integer>> pathSum(TreeNode root, int sum) { // write code here ArrayList<Integer> list = new ArrayList<>(); ArrayList<ArrayList<Integer>> lists = new ArrayList<>(); dfs(lists, list, 0, sum, root); return lists; } private static void dfs(ArrayList<ArrayList<Integer>> lists, ArrayList<Integer> list, int sum, int k, TreeNode root) { if (root == null) { return; } sum += root.val; list.add(root.val); if (root.left == null && root.right == null) { if (sum == k) { ArrayList<Integer> gg = new ArrayList<>(); for (int l : list) { gg.add(l); } //*注意list里面嵌入list的时候 改变里面的list会改变外层list 即添加进去的是引用* lists.add(gg); } list.remove(list.size() - 1); return; } dfs(lists, list, sum, k, root.left); dfs(lists, list, sum, k, root.right); list.remove(list.size() - 1); } public static class TreeNode { int val = 0; TreeNode left = null; TreeNode right = null; } public static void main(String[] args) { TreeNode node = new TreeNode(); node.val = 1; TreeNode leftChild = new TreeNode(); leftChild.val = 2; node.left = leftChild; ArrayList<ArrayList<Integer>> result = pathSum(node, 3); for (ArrayList<Integer> list : result) { System.out.println(list.toString()); } } }