topic:
An input and a binary integer, to print out all the paths of the binary tree and the node value is an integer input.
Starting from the root node down until the leaf node through the formation of a path.
Ideas:
In the preamble, in sequence, after traversing the tree, only preorder traversal is to first visit the root node.
When preorder before use to access a node, the node is added to the path, and the accumulated value of the node.
If the node is a leaf node and the path and node value just equal to the integer input, the current path to meet the requirements, we print it out.
If the current node is not a leaf node, then continue to access its child nodes. After the end of the current visit, recursive function will automatically return to its parent. So we want to remove before the function exits on the path to the current node and subtracting the value of the current node, just to make sure that the path is the path from the root to the parent when the parent returns.
Depth-first search
import java.util.ArrayList; import java.util.List; public class TwentySecond { public class BinarySearchTreeNode{ int val; BinarySearchTreeNode left; BinarySearchTreeNode right; } public static void findPath(BinarySearchTreeNode root, int expectedSum){ List<Integer> list = new ArrayList<>(); if(root != null){ findPath(root, 0, expectedSum, list); } } Public static void FindPath (BinarySearchTreeNode the root, int curSum, int expectedSum, List <Integer> Result) { // If the node is not empty processing proceeds IF (the root! = Null ) { // plus the current value of the node curSum + = root.val; // current node enqueue result.add (root.val); // if the current node is less than the desired value and IF (curSum < expectedSum) { // recursive process left subtree findPath (root. left, curSum, expectedSum, Result); // recursive process right subtree FindPath (root.right, curSum, expectedSum, Result); } // if the current and a desired equal and the else IF (curSum == expectedSum) { // the current node is a leaf node, the output IF (= root.left = null && root.right == null ) { System.out.println (Result); } } // remove the current node result.remove (result.size () -. 1 ); } } }