Check if a Binary Tree is an Even | Java Program for the above approach ; Tree node ; Function to return new tree node ; Function to check if the tree is even - odd tree ; Stores nodes of each level ; Store the current level of the binary tree ; Traverse until the queue is empty ; Stores the number of nodes present in the current level ; Check if the level is even or odd ; Add the nodes of the next level into the queue ; Increment the level count ; Driver Code ; Construct a Binary Tree ; Check if the binary tree is even - odd tree or not
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 isEvenOddBinaryTree ( Node root ) { if ( root == null ) return true ; Queue < Node > q = new LinkedList < > ( ) ; q . add ( root ) ; int level = 0 ; while ( ! q . isEmpty ( ) ) { int size = q . size ( ) ; for ( int i = 0 ; i < size ; i ++ ) { Node node = q . poll ( ) ; if ( level % 2 == 0 ) { if ( node . val % 2 == 1 ) return false ; } else if ( level % 2 == 1 ) { if ( node . val % 2 == 0 ) return false ; } if ( node . left != null ) { q . add ( node . left ) ; } if ( node . right != null ) { q . add ( node . right ) ; } } level ++ ; } return true ; } public static void main ( String [ ] args ) { Node root = null ; root = newNode ( 2 ) ; root . left = newNode ( 3 ) ; root . right = newNode ( 9 ) ; root . left . left = newNode ( 4 ) ; root . left . right = newNode ( 10 ) ; root . right . right = newNode ( 6 ) ; if ( isEvenOddBinaryTree ( root ) ) { System . out . println ( " YES " ) ; } else { System . out . println ( " NO " ) ; } } }