Smallest value in each level of Binary Tree | Python3 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 below diagram ; 7 / \ 6 5 / \ / \ 4 3 2 1
INT_MAX = 1000006 NEW_LINE class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def heightoftree ( root ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT left = heightoftree ( root . left ) ; NEW_LINE right = heightoftree ( root . right ) ; NEW_LINE return ( ( left if left > right else right ) + 1 ) ; NEW_LINE DEDENT def printPerLevelMinimum ( root , res , level ) : NEW_LINE INDENT if ( root != None ) : NEW_LINE INDENT res = printPerLevelMinimum ( root . left , res , level + 1 ) ; NEW_LINE if ( root . data < res [ level ] ) : NEW_LINE INDENT res [ level ] = root . data ; NEW_LINE DEDENT res = printPerLevelMinimum ( root . right , res , level + 1 ) ; NEW_LINE DEDENT return res NEW_LINE DEDENT def perLevelMinimumUtility ( root ) : NEW_LINE INDENT n = heightoftree ( root ) NEW_LINE i = 0 NEW_LINE res = [ INT_MAX for i in range ( n ) ] NEW_LINE res = printPerLevelMinimum ( root , res , 0 ) ; NEW_LINE print ( " Every ▁ level ▁ minimum ▁ is " ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT print ( ' level ▁ ' + str ( i ) + ' ▁ min ▁ is ▁ = ▁ ' + str ( res [ i ] ) ) NEW_LINE DEDENT DEDENT def newNode ( data ) : NEW_LINE INDENT temp = Node ( data ) NEW_LINE return temp ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT root = newNode ( 7 ) ; NEW_LINE root . left = newNode ( 6 ) ; NEW_LINE root . right = newNode ( 5 ) ; NEW_LINE root . left . left = newNode ( 4 ) ; NEW_LINE root . left . right = newNode ( 3 ) ; NEW_LINE root . right . left = newNode ( 2 ) ; NEW_LINE root . right . right = newNode ( 1 ) ; NEW_LINE perLevelMinimumUtility ( root ) ; NEW_LINE DEDENT