Question: Input a binary tree and an integer, print out all paths whose sum of node values in the binary tree is the input integer, starting from the root node of the tree and going down to the nodes passed by the leaf nodes to form a path
Analysis: Since the path starts from the root node to the leaf node, the root node must be traversed first, that is, preorder traversal. The rule is that preorder traversal visits a node, adds the node to the path, and accumulates the value of the node, if the node is a leaf node and the sum of the values of the nodes in the path is exactly equal to the input integer , the current path meets the requirements. If the current node is not a leaf node, continue to visit its child nodes. After the current node is visited, the recursive function will automatically return to its parent node, so before the function exits, delete the current node on the path and subtract the value of the current node to ensure that the path is just right when returning to the parent node is the path from the root node to the parent node.
import java.util. *; public class wr25findPath { public static ArrayList<ArrayList<Integer>> findPath(TreeNode root, int target){ ArrayList<ArrayList<Integer>> paths=new ArrayList<>(); if(root==null){ return paths; } find(paths,new ArrayList<Integer>(),root,target); return paths; } public static void find(ArrayList<ArrayList<Integer>> paths,ArrayList<Integer> path,TreeNode root, int target){ path.add(root.val); if(root.left==null && root.right==null){ // Reach the leaf node, join the path if satisfied, exit if not satisfied if(target==root.val){ paths.add(path); } return ; } ArrayList<Integer> path2=new ArrayList<>(); // path2 and path are equal, respectively responsible for the recursion of right and left branches path2.addAll(path); // If it is not a leaf node, traverse its child nodes if(root.left!=null){ find(paths,path,root.left,target-root.val); } if(root.right!=null){ find(paths,path2,root.right,target-root.val); } } public static void main(String []args){ TreeNode root=new TreeNode(10); root.left=new TreeNode(5); root.right=new TreeNode(12); root.left.left=new TreeNode(4); root.left.right=new TreeNode(7); ArrayList<ArrayList<Integer>> paths=findPath(root,22); for(int i=0;i<paths.size();i++){ ArrayList<Integer> list=paths.get(i); for(int j:list){ System.out.print(j+" "); } System.out.println(); } } }