Check if a Binary Tree contains node values in strictly increasing and decreasing order at even and odd levels | C ++ program for the above approach ; 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
#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 checkEvenOddLevel ( Node * root ) { if ( root == NULL ) return true ; queue < Node * > q ; q . push ( root ) ; int level = 0 ; while ( q . empty ( ) ) { vector < int > vec ; int size = q . size ( ) ; for ( int i = 0 ; i < size ; i ++ ) { Node * node = q . front ( ) ; vec . push_back ( node -> val ) ; if ( node -> left != NULL ) q . push ( node -> left ) ; if ( node -> right != NULL ) q . push ( node -> right ) ; } if ( level % 2 == 0 ) { for ( int i = 0 ; i < vec . size ( ) - 1 ; i ++ ) { if ( vec [ i + 1 ] > vec [ i ] ) continue ; return false ; } } else if ( level % 2 == 1 ) { for ( int i = 0 ; i < vec . size ( ) - 1 ; i ++ ) { if ( vec [ i + 1 ] < vec [ i ] ) continue ; return false ; } } level ++ ; } return true ; } int main ( ) { 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 ) ) cout << " YES " ; else cout << " NO " ; }