Construct the full k | Java program to build full k - ary tree from its preorder traversal and to print the postorder traversal of the tree . ; Structure of a node of an n - ary tree ; Utility function to create a new tree node with k children ; Function to build full k - ary tree ; For null tree ; For adding k children to a node ; Check if ind is in range of array Check if height of the tree is greater than 1 ; Recursively add each child ; Function to find the height of the tree ; Function to print postorder traversal of the tree ; Driver Code
import java . util . * ; class GFG { static class Node { int key ; Vector < Node > child ; } ; static Node newNode ( int value ) { Node nNode = new Node ( ) ; nNode . key = value ; nNode . child = new Vector < Node > ( ) ; return nNode ; } static int ind ; static Node BuildKaryTree ( int A [ ] , int n , int k , int h ) { if ( n <= 0 ) return null ; Node nNode = newNode ( A [ ind ] ) ; if ( nNode == null ) { System . out . println ( " Memory ▁ error " ) ; return null ; } for ( int i = 0 ; i < k ; i ++ ) { if ( ind < n - 1 && h > 1 ) { ind ++ ; nNode . child . add ( BuildKaryTree ( A , n , k , h - 1 ) ) ; } else { nNode . child . add ( null ) ; } } return nNode ; } static Node BuildKaryTree_1 ( int [ ] A , int n , int k , int in ) { int height = ( int ) Math . ceil ( Math . log ( ( double ) n * ( k - 1 ) + 1 ) / Math . log ( ( double ) k ) ) ; ind = in ; return BuildKaryTree ( A , n , k , height ) ; } static void postord ( Node root , int k ) { if ( root == null ) return ; for ( int i = 0 ; i < k ; i ++ ) postord ( root . child . get ( i ) , k ) ; System . out . print ( root . key + " ▁ " ) ; } public static void main ( String args [ ] ) { int ind = 0 ; int k = 3 , n = 10 ; int preorder [ ] = { 1 , 2 , 5 , 6 , 7 , 3 , 8 , 9 , 10 , 4 } ; Node root = BuildKaryTree_1 ( preorder , n , k , ind ) ; System . out . println ( " Postorder ▁ traversal ▁ of ▁ " + " constructed ▁ full ▁ k - ary ▁ tree ▁ is : ▁ " ) ; postord ( root , k ) ; System . out . println ( ) ; } }