Create loops of even and odd values in a binary tree | Utility function to create a new node ; preorder traversal to place the node pointer in the respective even_ptrs or odd_ptrs list ; place node ptr in even_ptrs list if node contains even number ; else place node ptr in odd_ptrs list ; function to create the even and odd loops ; forming even loop ; for the last element ; Similarly forming odd loop ; traversing the loop from any random node in the loop ; Binary tree formation ; traversing odd loop from any random odd node ; traversing even loop from any random even node
class Node { constructor ( data ) { this . data = data ; this . left = this . right = this . abtr = null ; } } let even_ptrs = [ ] ; let odd_ptrs = [ ] ; function preorderTraversal ( root ) { if ( root == null ) return ; if ( root . data % 2 == 0 ) ( even_ptrs ) . push ( root ) ; else ( odd_ptrs ) . push ( root ) ; preorderTraversal ( root . left ) ; preorderTraversal ( root . right ) ; } function createLoops ( root ) { preorderTraversal ( root ) ; let i ; for ( i = 1 ; i < even_ptrs . length ; i ++ ) even_ptrs [ i - 1 ] . abtr = even_ptrs [ i ] ; even_ptrs [ i - 1 ] . abtr = even_ptrs [ 0 ] ; for ( i = 1 ; i < odd_ptrs . length ; i ++ ) odd_ptrs [ i - 1 ] . abtr = odd_ptrs [ i ] ; odd_ptrs [ i - 1 ] . abtr = odd_ptrs [ 0 ] ; } function traverseLoop ( start ) { let curr = start ; do { document . write ( curr . data + " " ) ; curr = curr . abtr ; } while ( curr != start ) ; } let root = null ; root = new Node ( 1 ) ; root . left = new Node ( 2 ) ; root . right = new Node ( 3 ) ; root . left . left = new Node ( 4 ) ; root . left . right = new Node ( 5 ) ; root . right . left = new Node ( 6 ) ; root . right . right = new Node ( 7 ) ; createLoops ( root ) ; document . write ( " " ) ; traverseLoop ( root . right ) ; document . write ( " " ) ; traverseLoop ( root . left ) ;