Count nodes having smallest value in the path from root to itself in a Binary Tree | Python3 program for the above approach ; Class of a tree node ; Function to create new tree node ; Function to find the total number of required nodes ; If current node is null then return to the parent node ; Check if current node value is less than or equal to minNodeVal ; Update the value of minNodeVal ; Update the count ; Go to the left subtree ; Go to the right subtree ; Driver Code ; Binary Tree creation 8 / \ / \ 6 5 / \ / \ / \ / \ 6 7 3 9 ; Function Call ; Print the result
import sys NEW_LINE ans = 0 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 countReqNodes ( root , minNodeVal ) : NEW_LINE INDENT global ans NEW_LINE if root == None : NEW_LINE INDENT return NEW_LINE DEDENT if root . key <= minNodeVal : NEW_LINE INDENT minNodeVal = root . key NEW_LINE ans += 1 NEW_LINE DEDENT countReqNodes ( root . left , minNodeVal ) NEW_LINE countReqNodes ( root . right , minNodeVal ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = Node ( 8 ) NEW_LINE root . left = Node ( 6 ) NEW_LINE root . right = Node ( 5 ) NEW_LINE root . left . left = Node ( 6 ) NEW_LINE root . left . right = Node ( 7 ) NEW_LINE root . right . left = Node ( 3 ) NEW_LINE root . right . right = Node ( 9 ) NEW_LINE minNodeVal = sys . maxsize NEW_LINE countReqNodes ( root , minNodeVal ) NEW_LINE print ( ans ) NEW_LINE DEDENT