Print all root to leaf paths of an N | Java program for the above approach ; Structure of an N ary tree node ; Parameterized Constructor ; Function to print the root to leaf path of the given N - ary Tree ; Print elements in the vector ; Utility function to print all root to leaf paths of an Nary Tree ; If root is null ; Insert current node 's  data into the vector ; If current node is a leaf node ; Print the path ; Pop the leaf node and return ; Recur for all children of the current node ; Recursive Function Call ; Function to print root to leaf path ; If root is null , return ; Stores the root to leaf path ; Utility function call ; Driver Code ; Given N - Ary tree ; Function Call
import java . util . ArrayList ; class GFG { static class Node { int data ; ArrayList < Node > child ; public Node ( int x ) { this . data = x ; this . child = new ArrayList < > ( ) ; } } ; static void printPath ( ArrayList < Integer > vec ) { for ( int ele : vec ) { System . out . print ( ele + " ▁ " ) ; } System . out . println ( ) ; } static void printAllRootToLeafPaths ( Node root , ArrayList < Integer > vec ) { if ( root == null ) return ; vec . add ( root . data ) ; if ( root . child . isEmpty ( ) ) { printPath ( vec ) ; vec . remove ( vec . size ( ) - 1 ) ; return ; } for ( int i = 0 ; i < root . child . size ( ) ; i ++ ) printAllRootToLeafPaths ( root . child . get ( i ) , vec ) ; vec . remove ( vec . size ( ) - 1 ) ; } static void printAllRootToLeafPaths ( Node root ) { if ( root == null ) return ; ArrayList < Integer > vec = new ArrayList < > ( ) ; printAllRootToLeafPaths ( root , vec ) ; } public static void main ( String [ ] args ) { Node root = new Node ( 1 ) ; ( root . child ) . add ( new Node ( 2 ) ) ; ( root . child ) . add ( new Node ( 3 ) ) ; ( root . child . get ( 0 ) . child ) . add ( new Node ( 4 ) ) ; ( root . child . get ( 1 ) . child ) . add ( new Node ( 5 ) ) ; ( root . child . get ( 1 ) . child ) . add ( new Node ( 6 ) ) ; ( root . child . get ( 1 ) . child . get ( 1 ) . child ) . add ( new Node ( 7 ) ) ; ( root . child . get ( 1 ) . child . get ( 1 ) . child ) . add ( new Node ( 8 ) ) ; printAllRootToLeafPaths ( root ) ; } }