text: Check if a Binary Tree is an Even | C ++ 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
code: #include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int val ; Node * left , * right ; } ; struct Node * newNode ( int data ) { struct Node * temp = ( struct Node * ) malloc ( sizeof ( struct Node ) ) ; temp -> val = data ; temp -> left = NULL ; temp -> right = NULL ; return temp ; } bool isEvenOddBinaryTree ( Node * root ) { if ( root == NULL ) return true ; queue < Node * > q ; q . push ( root ) ; int level = 0 ; while ( ! q . empty ( ) ) { int size = q . size ( ) ; for ( int i = 0 ; i < size ; i ++ ) { Node * node = q . front ( ) ; if ( level % 2 == 0 ) { if ( node -> val % 2 == 1 ) return false ; } else if ( level % 2 == 1 ) { if ( node -> val % 2 == 0 ) return true ; } if ( node -> left != NULL ) { q . push ( node -> left ) ; } if ( node -> right != NULL ) { q . push ( node -> right ) ; } } level ++ ; } return true ; } int main ( ) { 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 ) ) cout << " YES " ; else cout << " NO " ; }