Binary tree and path to a certain value description of the topic
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.
Ideas
- Use the stack to store the path of the binary tree, traverse to the leaf node to determine whether the sum is the target, if it is printed, if it is not the leaf node, then continue to traverse the left and right sub-tree
- Note: When you finish printing, the leaf node of the top of the stack pops up when you return to the parent node, and the sum is subtracted from that value.
- Note: to traverse the stack when printing a path
Code
Import Java. util. ArrayList;Import Java. util.Stack;/**public class TreeNode {int val = 0; TreeNode left = null; TreeNode right = null; Public TreeNode (int val) {this.val = val;}} */public class Solution {Public arraylist<arraylist<Integer>> Findpath (TreeNode root,int target) {arraylist<arraylist<Integer>>List =New arraylist<arraylist<Integer>> ();if (root = =Null|| target = =0) {ReturnList }stack<Integer>stack =Newstack<Integer> (); Intsum =0; Find (Root,ListStacksum, target);ReturnList }Publicvoid find (TreeNode root, ArrayListListstack<Integer>Stack, intsum, int target) {sum + = root. val;Stack. push (Root. val);Boolean isleaf = (root. left = =Null&& (Root. right = =NULL);If it is a leaf node, and the sum equals target.Store the pathif ((sum = = target)&& isleaf) {arraylist<Integer> intlist =New arraylist<Integer> (); for (Integer x:Stack) {Intlist. Add (x);}List.add (intlist);} //if it is not a leaf node, traverse the left and right sub-nodes if (Rootnull) {find (Root.left, list, stack, sum, target);} if (Root.right! = null) {Find ( Root.right, list, stack, Span class= "Hljs-keyword" >sum, target);} //returns the parent node, deletes the current node sum-= Root.val; Stack.pop ()}}
Two fork tree and path to a value-sword point offer