This article describes the Java method to print all paths of the binary tree. Share it for your reference, as follows:
question:
Give a binary tree and print out all paths.
For example, for the following binary tree, all its paths are:
8 -> 3 -> 1
8 -> 2 -> 6 -> 4
8 -> 3 -> 6 -> 7
8 -> 10 -> 14 -> 13
Ideas:
Starting from the root node, put your own value in an array, and then pass this array to its child node. The child node also puts its own value in this array, and passes it to its child node until this node is a leaf node, and then prints the array out. So, we need to use recursion here.
Code:
/**Given a binary tree, prints out all of its root-to-leafpaths, one per line. Uses a recursive helper to do the work.*/public void printPaths(Node root, int n) { String[] path = new String[n]; printPaths(root, path, 0);}/**Recursive printPaths helper -- given a node, and an array containing the path from the root node up to but not including this node,prints out all the root-leaf paths.*/private void printPaths(Node node, String[] path, int pathLen) { if (node == null) return; // append this node to the path array path[pathLen++] = node.value; // it's a leaf, so print the path that led to here if (node.leftChild == null && node.rightChild == null) { printArray(path, pathLen); } else { // otherwise try both subtrees printPaths(node.leftChild, path, pathLen); printPaths(node.rightChild, path, pathLen); }}/**Utility that prints strings from an array on one line.*/private void printArray(String[] ints, int len) { for (int i = 0; i < len; i++) { System.out.print(ints[i] + " "); } System.out.println();}Note: You can only use an array + a value to print the required path. If you use a linked list structure such as linkedlist, it will not work. It's worth analyzing the reasons, it's very interesting.
For more information about Java algorithms, readers who are interested in this site can view the topics: "Java Data Structure and Algorithm Tutorial", "Summary of Java Operation DOM Node Tips", "Summary of Java File and Directory Operation Tips" and "Summary of Java Cache Operation Tips"
I hope this article will be helpful to everyone's Java programming.