Creating a tree with Left | JavaScript 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
class Node { constructor ( data ) { this . data = data ; this . next = this . child = null ; } } function addSibling ( n , data ) { if ( n == null ) return null ; while ( n . next != null ) n = n . next ; return ( n . next = new Node ( data ) ) ; } function addChild ( n , data ) { if ( n == null ) return null ; if ( n . child != null ) return addSibling ( n . child , data ) ; else return ( n . child = new Node ( data ) ) ; } function traverseTree ( root ) { if ( root == null ) return ; document . write ( root . data + " " ) ; if ( root . child == null ) return ; let q = [ ] ; let curr = root . child ; q . push ( curr ) ; while ( q . length != 0 ) { curr = q [ 0 ] ; q . shift ( ) ; while ( curr != null ) { document . write ( curr . data + " " ) ; if ( curr . child != null ) { q . push ( curr . child ) ; } curr = curr . next ; } } } let root = new Node ( 10 ) ; let n1 = addChild ( root , 2 ) ; let n2 = addChild ( root , 3 ) ; let n3 = addChild ( root , 4 ) ; let n4 = addChild ( n3 , 6 ) ; let n5 = addChild ( root , 5 ) ; let n6 = addChild ( n5 , 7 ) ; let n7 = addChild ( n5 , 8 ) ; let n8 = addChild ( n5 , 9 ) ; traverseTree ( root ) ;