Count nodes from all lower levels smaller than minimum valued node of current level for every level in a Binary Tree | ''Python3 program of the above approach ; ''Stores the nodes to be deleted ; ''Structure of a Tree node ; ''Function to find the min value of node for each level ; '' Count is used to diffentiate  each level of the tree ; ''Function to check whether the nodes in the level below it are smaller by performing post order traversal ; '' Traverse the left subtree ; '' Traverse right subtree ; '' Check from minimum values  computed at each level ; ''Function to print count of nodes from all lower levels having values less than the the nodes in the current level ; '' Stores the number of levels ; '' Stores the required count  of nodes for each level ; ''Driver Code ; ''  4  / \  3 5  / \ / \  10 2 3 1
from collections import deque NEW_LINE from sys import maxsize as INT_MAX NEW_LINE mp = dict ( ) NEW_LINE class Node : NEW_LINE INDENT def __init__ ( self , key ) : NEW_LINE INDENT self . key = key NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def calculateMin ( root : Node , levelMin : list ) -> None : NEW_LINE INDENT qt = deque ( ) NEW_LINE qt . append ( root ) NEW_LINE count = 1 NEW_LINE min_v = INT_MAX NEW_LINE while ( qt ) : NEW_LINE INDENT temp = qt . popleft ( ) NEW_LINE min_v = min ( min_v , temp . key ) NEW_LINE if ( temp . left ) : NEW_LINE INDENT qt . append ( temp . left ) NEW_LINE DEDENT if ( temp . right ) : NEW_LINE INDENT qt . append ( temp . right ) NEW_LINE DEDENT count -= 1 NEW_LINE if ( count == 0 ) : NEW_LINE INDENT levelMin . append ( min_v ) NEW_LINE min_v = INT_MAX NEW_LINE count = len ( qt ) NEW_LINE DEDENT DEDENT DEDENT def findNodes ( root : Node , levelMin : list , levelResult : list , level : int ) -> None : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return NEW_LINE DEDENT findNodes ( root . left , levelMin , levelResult , level + 1 ) NEW_LINE findNodes ( root . right , levelMin , levelResult , level + 1 ) NEW_LINE for i in range ( level ) : NEW_LINE INDENT if ( root . key <= levelMin [ i ] ) : NEW_LINE INDENT levelResult [ i ] += 1 NEW_LINE DEDENT DEDENT DEDENT def printNodes ( root : Node ) -> None : NEW_LINE INDENT levelMin = [ ] NEW_LINE calculateMin ( root , levelMin ) NEW_LINE numLevels = len ( levelMin ) NEW_LINE levelResult = [ 0 ] * numLevels NEW_LINE findNodes ( root , levelMin , levelResult , 0 ) NEW_LINE for i in range ( numLevels ) : NEW_LINE INDENT print ( levelResult [ i ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT root = Node ( 4 ) NEW_LINE root . left = Node ( 3 ) NEW_LINE root . right = Node ( 5 ) NEW_LINE root . right . left = Node ( 3 ) NEW_LINE root . right . right = Node ( 1 ) NEW_LINE root . left . left = Node ( 10 ) NEW_LINE root . left . right = Node ( 2 ) NEW_LINE printNodes ( root ) NEW_LINE DEDENT