Enter a binary tree and an integer to print out all paths for the value of the node in the two-fork tree and for the input integer. A path is defined as a path from the root node of the tree down to the node through which the leaf nodes go.
/** * Enter a binary tree and an integer to print out all paths for the value of the node in the two-fork tree and for the input integer. * The path is defined as a path from the root node of the tree down to the node through which the leaf nodes go. * In fact, I did not think of the first sequence traversal, but with a similar deep search method, continue to go down until the leaf node is found * and then see if sum is equal to the target * but there is a problem is, after traversing the left child of a node, when traversing the right child, the left child was found to stay in the list. * One way to do this is to create an identical list before traversing, which is the extra space consumed. * With the first order traversal in fact the same way, but with a stack to maintain, after traversing a node of the left and right children, you need to put this point out of the stack. * @author Admin * */public class Pathsum {public static arraylist<arraylist<integer>> results=new ARRAYLIST&L T Arraylist<integer>> (); public static arraylist<arraylist<integer>> Findpath (TreeNode root,int target) {if (root==null| | Target<root.val) {return results; } findpath (Root,0,target,new arraylist<integer> ()); return results; } public static void Findpath (TreeNode current,int sum,int target,arraylist<integer> stack) {if (current!=null) {St Ack.add (Current.val); Sum+=current.val; if (current.left==null&¤t.right==null) {if (sum==target) {///If Sum==target is added to the result set Results.add (new Arraylist<integer> (Stack)); }//If not equal, the stack is also required, so there is no return} if (Current.left!=null) {Findpath (current.left,sum,target,stack);} if (current.right!= NULL) {Findpath (current.right,sum,target,stack);}//current node out stack stack.remove (Stack.size ()-1); } }}
Sword refers to the offer-of a path in a two fork tree and is given a value