Smallest value in each level of Binary Tree | Java program to print smallest element in each level of binary tree . ; A Binary Tree Node ; return height of tree ; Inorder Traversal Search minimum element in each level and store it into vector array . ; height of tree for the size of vector array ; vector for store all minimum of every level ; save every level minimum using inorder traversal ; print every level minimum ; 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 . Arrays ; class GFG { static int INT_MAX = ( int ) 10e6 ; 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 , int [ ] res , int level ) { if ( root != null ) { printPerLevelMinimum ( root . left , res , level + 1 ) ; if ( root . data < res [ level ] ) res [ level ] = root . data ; printPerLevelMinimum ( root . right , res , level + 1 ) ; } } static void perLevelMinimumUtility ( Node root ) { int n = heightoftree ( root ) , i ; int [ ] res = new int [ n ] ; Arrays . fill ( res , INT_MAX ) ; printPerLevelMinimum ( root , res , 0 ) ; System . out . print ( "Every level minimum isNEW_LINE"); for ( i = 0 ; i < n ; i ++ ) { System . out . print ( " level ▁ " + i + " ▁ min ▁ is ▁ = ▁ " + res [ i ] + "NEW_LINE"); } } 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 ) ; perLevelMinimumUtility ( root ) ; } }