Smallest value in each level of Binary Tree | CPP program to print minimum element in each level of binary tree . ; A Binary Tree Node ; return height of tree ; Iterative method to find every level minimum element of Binary Tree ; Base Case ; Create an empty queue for level order traversal ; push the root for Change the level ; for go level by level ; for check the level ; Get top of queue ; if node == NULL ( Means this is boundary between two levels ) ; here queue is empty represent no element in the actual queue ; increment level ; Reset min for next level minimum value ; get Minimum in every level ; Enqueue left child ; Enqueue right child ; Utility function to create a new tree node ; Driver program to test above functions ; Let us create binary tree shown in above diagram ; 7 / \ 6 5 / \ / \ 4 3 2 1
#include <iostream> NEW_LINE #include <queue> NEW_LINE #include <vector> NEW_LINE #define INT_MAX  10e6 NEW_LINE using namespace std ; struct Node { int data ; struct Node * left , * right ; } ; int heightoftree ( Node * root ) { if ( root == NULL ) return 0 ; int left = heightoftree ( root -> left ) ; int right = heightoftree ( root -> right ) ; return ( ( left > right ? left : right ) + 1 ) ; } void printPerLevelMinimum ( Node * root ) { if ( root == NULL ) return ; queue < Node * > q ; q . push ( root ) ; q . push ( NULL ) ; int min = INT_MAX ; int level = 0 ; while ( q . empty ( ) == false ) { Node * node = q . front ( ) ; q . pop ( ) ; if ( node == NULL ) { cout << " level ▁ " << level << " ▁ min ▁ is ▁ = ▁ " << min << " STRNEWLINE " ; if ( q . empty ( ) ) break ; q . push ( NULL ) ; level ++ ; min = INT_MAX ; continue ; } if ( min > node -> data ) min = node -> data ; if ( node -> left != NULL ) { q . push ( node -> left ) ; } if ( node -> right != NULL ) { q . push ( node -> right ) ; } } } Node * newNode ( int data ) { Node * temp = new Node ; temp -> data = data ; temp -> left = temp -> right = NULL ; return temp ; } int main ( ) { Node * root = newNode ( 7 ) ; root -> left = newNode ( 6 ) ; root -> right = newNode ( 5 ) ; root -> left -> left = newNode ( 4 ) ; root -> left -> right = newNode ( 3 ) ; root -> right -> left = newNode ( 2 ) ; root -> right -> right = newNode ( 1 ) ; cout << " Every ▁ Level ▁ minimum ▁ is " << " STRNEWLINE " ; printPerLevelMinimum ( root ) ; return 0 ; }