Count nodes having smallest value in the path from root to itself in a Binary Tree | Structure of 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 ; Binary Tree creation 8 / \ / \ 6 5 / \ / \ / \ / \ 6 7 3 9 ; Function Call ; Print the result
class Node { constructor ( key ) { this . left = null ; this . right = null ; this . key = key ; } } function newNode ( key ) { let temp = new Node ( key ) ; return temp ; } let ans ; function countReqNodes ( root , minNodeVal ) { if ( root == null ) return ; if ( root . key <= minNodeVal ) { minNodeVal = root . key ; ans ++ ; } countReqNodes ( root . left , minNodeVal ) ; countReqNodes ( root . right , minNodeVal ) ; } let root = newNode ( 8 ) ; root . left = newNode ( 6 ) ; root . right = newNode ( 5 ) ; root . left . left = newNode ( 6 ) ; root . left . right = newNode ( 7 ) ; root . right . left = newNode ( 3 ) ; root . right . right = newNode ( 9 ) ; let minNodeVal = Number . MAX_VALUE ; ans = 0 ; countReqNodes ( root , minNodeVal ) ; document . write ( ans ) ;