Check if all leaves are at same level | C ++ program to check if all leaf nodes are at same level of binary tree ; tree node ; returns a new tree Node ; return true if all leaf nodes are at same level , else false ; create a queue for level order traversal ; traverse until the queue is empty ; traverse for complete level ; check for left child ; if its leaf node ; if it 's first leaf node, then update result ; if it 's not first leaf node, then compare  the level with level of previous leaf node ; check for right child ; if it 's leaf node ; if it 's first leaf node till now,  then update the result ; if it is not the first leaf node , then compare the level with level of previous leaf node ; driver program ; construct a tree
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; Node * left , * right ; } ; Node * newNode ( int data ) { Node * temp = new Node ( ) ; temp -> data = data ; temp -> left = temp -> right = NULL ; return temp ; } int checkLevelLeafNode ( Node * root ) { if ( ! root ) return 1 ; queue < Node * > q ; q . push ( root ) ; int result = INT_MAX ; int level = 0 ; while ( ! q . empty ( ) ) { int size = q . size ( ) ; level += 1 ; while ( size > 0 ) { Node * temp = q . front ( ) ; q . pop ( ) ; if ( temp -> left ) { q . push ( temp -> left ) ; if ( ! temp -> left -> right && ! temp -> left -> left ) { if ( result == INT_MAX ) result = level ; else if ( result != level ) return 0 ; } } if ( temp -> right ) { q . push ( temp -> right ) ; if ( ! temp -> right -> left && ! temp -> right -> right ) if ( result == INT_MAX ) result = level ; else if ( result != level ) return 0 ; } size -= 1 ; } } return 1 ; } int main ( ) { Node * root = newNode ( 1 ) ; root -> left = newNode ( 2 ) ; root -> right = newNode ( 3 ) ; root -> left -> right = newNode ( 4 ) ; root -> right -> left = newNode ( 5 ) ; root -> right -> right = newNode ( 6 ) ; int result = checkLevelLeafNode ( root ) ; if ( result ) cout << " All ▁ leaf ▁ nodes ▁ are ▁ at ▁ same ▁ level STRNEWLINE " ; else cout << " Leaf ▁ nodes ▁ not ▁ at ▁ same ▁ level STRNEWLINE " ; return 0 ; }