Creating a tree with Left | Java program to create a tree with left child right sibling representation . ; Creating new Node ; Adds a sibling to a list with starting with n ; Add child Node to a Node ; Check if child list is not empty . ; Traverses tree in level order ; Corner cases ; Create a queue and enque root ; Take out an item from the queue ; Print next level of taken out item and enque next level 's children ; Driver code
import java . util . * ; class GFG { static class Node { int data ; Node next ; Node child ; } ; static Node newNode ( int data ) { Node newNode = new Node ( ) ; newNode . next = newNode . child = null ; newNode . data = data ; return newNode ; } static Node addSibling ( Node n , int data ) { if ( n == null ) return null ; while ( n . next != null ) n = n . next ; return ( n . next = newNode ( data ) ) ; } static Node addChild ( Node n , int data ) { if ( n == null ) return null ; if ( n . child != null ) return addSibling ( n . child , data ) ; else return ( n . child = newNode ( data ) ) ; } static void traverseTree ( Node root ) { if ( root == null ) return ; System . out . print ( root . data + " ▁ " ) ; if ( root . child == null ) return ; Queue < Node > q = new LinkedList < > ( ) ; Node curr = root . child ; q . add ( curr ) ; while ( ! q . isEmpty ( ) ) { curr = q . peek ( ) ; q . remove ( ) ; while ( curr != null ) { System . out . print ( curr . data + " ▁ " ) ; if ( curr . child != null ) { q . add ( curr . child ) ; } curr = curr . next ; } } } public static void main ( String [ ] args ) { Node root = newNode ( 10 ) ; Node n1 = addChild ( root , 2 ) ; Node n2 = addChild ( root , 3 ) ; Node n3 = addChild ( root , 4 ) ; Node n4 = addChild ( n3 , 6 ) ; Node n5 = addChild ( root , 5 ) ; Node n6 = addChild ( n5 , 7 ) ; Node n7 = addChild ( n5 , 8 ) ; Node n8 = addChild ( n5 , 9 ) ; traverseTree ( root ) ; } }