Check if a Binary Tree contains node values in strictly increasing and decreasing order at even and odd levels | Java Program for the above approach ; Structure of Tree node ; Function to create new Tree node ; Function to check if given binary tree satisfies the required conditions ; Queue to store nodes of each level ; Stores the current level of the binary tree ; Traverse until the queue is empty ; Stores the number of nodes present in the current level ; Insert left and right child of node into the queue ; If the level is even ; If the nodes in this level are in strictly increasing order or not ; If the level is odd ; If the nodes in this level are in strictly decreasing order or not ; Increment the level count ; Driver Code ; Construct a Binary Tree ; Function Call
import java . util . * ; class GFG { static class Node { int val ; Node left , right ; } static Node newNode ( int data ) { Node temp = new Node ( ) ; temp . val = data ; temp . left = null ; temp . right = null ; return temp ; } public static boolean checkEvenOddLevel ( Node root ) { if ( root == null ) return true ; Queue < Node > q = new LinkedList < > ( ) ; q . add ( root ) ; int level = 0 ; while ( ! q . isEmpty ( ) ) { ArrayList < Integer > list = new ArrayList < > ( ) ; int size = q . size ( ) ; for ( int i = 0 ; i < size ; i ++ ) { Node node = q . poll ( ) ; list . add ( node . val ) ; if ( node . left != null ) q . add ( node . left ) ; if ( node . right != null ) q . add ( node . right ) ; } if ( level % 2 == 0 ) { for ( int i = 0 ; i < list . size ( ) - 1 ; i ++ ) { if ( list . get ( i + 1 ) > list . get ( i ) ) continue ; return false ; } } else if ( level % 2 == 1 ) { for ( int i = 0 ; i < list . size ( ) - 1 ; i ++ ) { if ( list . get ( i + 1 ) < list . get ( i ) ) continue ; return false ; } } level ++ ; } return true ; } public static void main ( String [ ] args ) { Node root = null ; root = newNode ( 2 ) ; root . left = newNode ( 6 ) ; root . right = newNode ( 3 ) ; root . left . left = newNode ( 4 ) ; root . left . right = newNode ( 7 ) ; root . right . right = newNode ( 11 ) ; root . left . left . left = newNode ( 10 ) ; root . left . left . right = newNode ( 5 ) ; root . left . right . right = newNode ( 1 ) ; if ( checkEvenOddLevel ( root ) ) { System . out . println ( " YES " ) ; } else { System . out . println ( " NO " ) ; } } }