package org.example.test; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import java.awt.*; import java.util.ArrayList; import java.util.LinkedList; import java.util.Queue; public class DFSTest { static ArrayList<Boolean> vis = new ArrayList<>(); public static void main(String[] args) { TreeNode node1 = new TreeNode(5); TreeNode node2 = new TreeNode(4); TreeNode node3 = new TreeNode(8); node1.left = node2; node1.right = node3; TreeNode node4 = new TreeNode(1); TreeNode node5 = new TreeNode(11); node2.left = node4; node2.right = node5; TreeNode node6 = new TreeNode(9); node3.right = node6; TreeNode node7 = new TreeNode(2); TreeNode node8 = new TreeNode(7); node5.left = node7; node5.right = node8; System.out.println(JSONObject.toJSONString(pathSum(node1, 22))); } public static class TreeNode { int val = 0; TreeNode left = null; TreeNode right = null; public TreeNode(int val) { this.val = val; } } public static ArrayList<ArrayList<Integer>> pathSum(TreeNode root, int sum) { // write code here ArrayList<ArrayList<Integer>> ret = new ArrayList<>(); if (root == null) { return ret; } LinkedList<Integer> path = new LinkedList<>(); path.add(root.val); getPath(root, ret, path, sum - root.val); return ret; } private static void getPath(TreeNode root, ArrayList<ArrayList<Integer>> ret, LinkedList<Integer> path, int sum) { if (root.left == null && root.right == null) { System.out.println(root.val); if (sum == 0) { ret.add(new ArrayList<>(path)); } return; } if (root.left != null) { path.add(root.left.val); getPath(root.left, ret, path, sum - root.left.val); path.removeLast(); } if (root.right != null) { path.add(root.right.val); getPath(root.right, ret, path, sum - root.right.val); path.removeLast(); } } public static void dfs(TreeNode root, ArrayList<ArrayList<Integer>> ret, LinkedList<Integer> path, int target) { if (root == null) { return; } path.add(root.val); target -= root.val; if (root.left == null && root.right == null && target == 0) { ret.add(new ArrayList<>(path)); } dfs(root.left, ret, path, target); dfs(root.right, ret, path, target); path.removeLast(); } }