Smallest value in each level of Binary Tree | Python3 program to prminimum element in each level of binary tree . Importing Queue ; Utility class to create a new tree node ; return height of tree p ; Iterative method to find every level minimum element of Binary Tree ; Base Case ; Create an empty queue for level order traversal ; put the root for Change the level ; for go level by level ; for check the level ; Get get of queue ; if node == None ( 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 ; Driver Code ; Let us create binary tree shown in above diagram ; 7 / \ 6 5 / \ / \ 4 3 2 1
from queue import Queue NEW_LINE class newNode : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = 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 if left > right : NEW_LINE INDENT return left + 1 NEW_LINE DEDENT else : NEW_LINE INDENT return right + 1 NEW_LINE DEDENT DEDENT def printPerLevelMinimum ( root ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return NEW_LINE DEDENT q = Queue ( ) NEW_LINE q . put ( root ) NEW_LINE q . put ( None ) NEW_LINE Min = 9999999999999 NEW_LINE level = 0 NEW_LINE while ( q . empty ( ) == False ) : NEW_LINE INDENT node = q . queue [ 0 ] NEW_LINE q . get ( ) NEW_LINE if ( node == None ) : NEW_LINE INDENT print ( " level " , level , " min ▁ is ▁ = " , Min ) NEW_LINE if ( q . empty ( ) ) : NEW_LINE INDENT break NEW_LINE DEDENT q . put ( None ) NEW_LINE level += 1 NEW_LINE Min = 999999999999 NEW_LINE continue NEW_LINE DEDENT if ( Min > node . data ) : NEW_LINE INDENT Min = node . data NEW_LINE DEDENT if ( node . left != None ) : NEW_LINE INDENT q . put ( node . left ) NEW_LINE DEDENT if ( node . right != None ) : NEW_LINE INDENT q . put ( node . right ) NEW_LINE DEDENT DEDENT 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 print ( " Every ▁ Level ▁ minimum ▁ is " ) NEW_LINE printPerLevelMinimum ( root ) NEW_LINE DEDENT