Create loops of even and odd values in a binary tree | Java implementation to create odd and even loops in a binary tree ; structure of a node ; 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 ; Driver code ; Binary tree formation ; traversing odd loop from any random odd node ; traversing even loop from any random even node
import java . util . * ; class GFG { static class Node { int data ; Node left , right , abtr ; } ; static Node newNode ( int data ) { Node node = new Node ( ) ; node . data = data ; node . left = node . right = node . abtr = null ; return node ; } static Vector < Node > even_ptrs = new Vector < > ( ) ; static Vector < Node > odd_ptrs = new Vector < > ( ) ; static void preorderTraversal ( Node root ) { if ( root == null ) return ; if ( root . data % 2 == 0 ) ( even_ptrs ) . add ( root ) ; else ( odd_ptrs ) . add ( root ) ; preorderTraversal ( root . left ) ; preorderTraversal ( root . right ) ; } static void createLoops ( Node root ) { preorderTraversal ( root ) ; int i ; for ( i = 1 ; i < even_ptrs . size ( ) ; i ++ ) even_ptrs . get ( i - 1 ) . abtr = even_ptrs . get ( i ) ; even_ptrs . get ( i - 1 ) . abtr = even_ptrs . get ( 0 ) ; for ( i = 1 ; i < odd_ptrs . size ( ) ; i ++ ) odd_ptrs . get ( i - 1 ) . abtr = odd_ptrs . get ( i ) ; odd_ptrs . get ( i - 1 ) . abtr = odd_ptrs . get ( 0 ) ; } static void traverseLoop ( Node start ) { Node curr = start ; do { System . out . print ( curr . data + " ▁ " ) ; curr = curr . abtr ; } while ( curr != start ) ; } public static void main ( String [ ] args ) { Node root = null ; root = newNode ( 1 ) ; root . left = newNode ( 2 ) ; root . right = newNode ( 3 ) ; root . left . left = newNode ( 4 ) ; root . left . right = newNode ( 5 ) ; root . right . left = newNode ( 6 ) ; root . right . right = newNode ( 7 ) ; createLoops ( root ) ; System . out . print ( " Odd ▁ nodes : ▁ " ) ; traverseLoop ( root . right ) ; System . out . print ( " Even nodes : "); traverseLoop ( root . left ) ; } }