Print characters and their frequencies in order of occurrence using Binary Tree | Node in the tree where data holds the character of the String and cnt holds the frequency ; Function to add a new node to the Binary Tree ; Create a new node and populate its data part , set cnt as 1 and left and right children as null ; Function to add a node to the Binary Tree in level order ; Use the queue data structure for level order insertion and push the root of tree to Queue ; If the character to be inserted is present , update the cnt ; If the left child is empty add a new node as the left child ; If the character is present as a left child , update the cnt and exit the loop ; push the left child to the queue for further processing ; If the right child is empty , add a new node to the right ; If the character is present as a right child , update the cnt and exit the loop ; push the right child to the queue for further processing ; Function to print the level order traversal of the Binary Tree ; push the root to the queue ; If the cnt of the character is more then one , display cnt ; If the cnt of character is one , display character only ; push the left child to the queue for further processing ; push the right child to the queue for further processing ; Driver code ; push individual characters to the String one by one in level order ; Print the level order of the constructed binary tree
class node { constructor ( ) { this . data = ' ' ; this . cnt = 0 ; this . left = null ; this . right = null ; } } ; function add ( data ) { var newnode = new node ( ) ; newnode . data = data ; newnode . cnt = 1 ; newnode . left = newnode . right = null ; return newnode ; } function addinlvlorder ( root , data ) { if ( root == null ) { return add ( data ) ; } var Q = [ ] ; Q . push ( root ) ; while ( Q . length != 0 ) { var temp = Q [ 0 ] ; Q . shift ( ) ; if ( temp . data == data ) { temp . cnt ++ ; break ; } if ( temp . left == null ) { temp . left = add ( data ) ; break ; } else { if ( temp . left . data == data ) { temp . left . cnt ++ ; break ; } Q . push ( temp . left ) ; } if ( temp . right == null ) { temp . right = add ( data ) ; break ; } else { if ( temp . right . data == data ) { temp . right . cnt ++ ; break ; } Q . push ( temp . right ) ; } } return root ; } function printlvlorder ( root ) { var Q = [ ] ; Q . push ( root ) ; while ( Q . length != 0 ) { var temp = Q [ 0 ] ; if ( temp . cnt > 1 ) { document . write ( ( temp . data + " " + temp . cnt ) ) ; } else { document . write ( temp . data ) ; } Q . shift ( ) ; if ( temp . left != null ) { Q . push ( temp . left ) ; } if ( temp . right != null ) { Q . push ( temp . right ) ; } } } var s = " " ; var root = null ; for ( var i = 0 ; i < s . length ; i ++ ) { root = addinlvlorder ( root , s [ i ] ) ; } printlvlorder ( root ) ;