1 Importjava.util.ArrayList;2 3 /**4 * Find the shortest two-fork search path, from the root node to the leaf node.5 * 6 * @authorJinfeng7 *8 */9 Public classFindshortestbtpath {Ten One //used to record all paths. A PrivateArraylist<arraylist<integer>> allpaths =NewArraylist<arraylist<integer>>(); - //used to record a path - PrivateArraylist<integer> OnePath =NewArraylist<integer>(); the - //return all the paths - PublicArraylist<arraylist<integer>>Findallpath (TreeNode root) { - if(Root = =NULL) + returnallpaths; - + //Add the current node to the path. A Onepath.add (root.val); at - //if it is a leaf node, add the OnePath to the allpaths. - if(Root.left = =NULL&& Root.right = =NULL){ -Allpaths.add (NewArraylist<integer>(OnePath)); - } - in Findallpath (root.left); - Findallpath (root.right); to + //This place can be understood by drawing a recursive tree, regardless of whether the leaf node is the left or the right node, it will go through the following step, and is of paramount importance . -Onepath.remove (Onepath.size ()-1); the returnallpaths; * } $ Panax Notoginseng Public Static voidMain (string[] args) { - the } + A } the + classTreeNode { - intval = 0; $TreeNode left =NULL; $TreeNode right =NULL; - - PublicTreeNode (intval) { the This. val =Val; - Wuyi } the -}
All paths in the binary tree (from the root node to the leaf node)