Example:
Output for the above example will be
1 2 4 1 2 5 1 3
Solution:
// Java program to print all root to leaf paths/* A binary tree node has data, pointer to left childand a pointer to right child */classNode{intdata;Node left, right;Node(intitem){data = item;left = right =null;}}classBinaryTree{Node root;/* Given a binary tree, print out all of its root-to-leafpaths, one per line. Uses a recursive helper to do the work.*/voidprintPaths(Node node){intpath[] =newint[1000];printPathsRecur(node, path,0);}/* Recursive helper function -- given a node, and an array containingthe path from the root node up to but not including this node,print out all the root-leaf paths. */voidprintPathsRecur(Node node,intpath[],intpathLen){if(node ==null)return;/* append this node to the path array */path[pathLen] = node.data;pathLen++;/* it's a leaf, so print the path that led to here */if(node.left ==null&& node.right ==null)printArray(path, pathLen);else{/* otherwise try both subtrees */printPathsRecur(node.left, path, pathLen);printPathsRecur(node.right, path, pathLen);}}/* Utility that prints out an array on a line */voidprintArray(intints[],intlen){inti;for(i =0; i < len; i++)System.out.print(ints[i] +" ");System.out.println("");}/* Driver program to test all above functions */publicstaticvoidmain(String[] args){BinaryTree tree =newBinaryTree();tree.root =newNode(1);tree.root.left =newNode(2);tree.root.right =newNode(3);tree.root.left.left =newNode(4);tree.root.left.right =newNode(5);/* Print all root-to-leaf paths of the input tree */tree.printPaths(tree.root);}}

No comments:
Post a Comment