Smallest value in each level of Binary Tree | JAVA 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 code ; Let us create binary tree shown in above diagram ; 7 / \ 6 5 / \ / \ 4 3 2 1
import java . util . * ; class GFG { static class Node { int data ; Node left , right ; } ; static 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 ) ; } static void printPerLevelMinimum ( Node root ) { if ( root == null ) return ; Queue < Node > q = new LinkedList < Node > ( ) ; q . add ( root ) ; q . add ( null ) ; int min = Integer . MAX_VALUE ; int level = 0 ; while ( q . isEmpty ( ) == false ) { Node node = q . peek ( ) ; q . remove ( ) ; if ( node == null ) { System . out . print ( " level ▁ " + level + " ▁ min ▁ is ▁ = ▁ " + min + "NEW_LINE"); if ( q . isEmpty ( ) ) break ; q . add ( null ) ; level ++ ; min = Integer . MAX_VALUE ; continue ; } if ( min > node . data ) min = node . data ; if ( node . left != null ) { q . add ( node . left ) ; } if ( node . right != null ) { q . add ( node . right ) ; } } } static Node newNode ( int data ) { Node temp = new Node ( ) ; temp . data = data ; temp . left = temp . right = null ; return temp ; } public static void main ( String [ ] args ) { 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 ) ; System . out . print ( " Every ▁ Level ▁ minimum ▁ is " + "NEW_LINE"); printPerLevelMinimum ( root ) ; } }