Check if the Left View of the given tree is sorted or not | C ++ implementation to Check if the Left View of the given tree is Sorted or not ; Binary Tree Node ; Utility function to create a new node ; Function to find left view and check if it is sorted ; queue to hold values ; variable to check whether level order is sorted or not ; Iterate until the queue is empty ; Traverse every level in tree ; variable for initial level ; checking values are sorted or not ; Push left value if it is not null ; Push right value if it is not null ; Pop out the values from queue ; Check if the value are not sorted then break the loop ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct node { int val ; struct node * right , * left ; } ; struct node * newnode ( int key ) { struct node * temp = new node ; temp -> val = key ; temp -> right = NULL ; temp -> left = NULL ; return temp ; } void func ( node * root ) { queue < node * > q ; bool t = true ; q . push ( root ) ; int i = -1 , j = -1 , k = -1 ; while ( ! q . empty ( ) ) { int h = q . size ( ) ; while ( h > 0 ) { root = q . front ( ) ; if ( i == -1 ) { j = root -> val ; } if ( i == -2 ) { if ( j <= root -> val ) { j = root -> val ; i = -3 ; } else { t = false ; break ; } } if ( root -> left != NULL ) { q . push ( root -> left ) ; } if ( root -> right != NULL ) { q . push ( root -> right ) ; } h = h - 1 ; q . pop ( ) ; } i = -2 ; if ( t == false ) { break ; } } if ( t ) cout << " true " << endl ; else cout << " false " << endl ; } int main ( ) { struct node * root = newnode ( 10 ) ; root -> right = newnode ( 50 ) ; root -> right -> right = newnode ( 15 ) ; root -> left = newnode ( 20 ) ; root -> left -> left = newnode ( 50 ) ; root -> left -> right = newnode ( 23 ) ; root -> right -> left = newnode ( 10 ) ; func ( root ) ; return 0 ; }