Count nodes having smallest value in the path from root to itself in a Binary Tree | Java program for the above approach ; Structure 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 java . util . * ; class GFG { static class Node { int key ; Node left , right ; } ; static Node newNode ( int key ) { Node temp = new Node ( ) ; temp . key = key ; temp . left = temp . right = null ; return temp ; } static int ans ; static void countReqNodes ( Node root , int minNodeVal ) { if ( root == null ) return ; if ( root . key <= minNodeVal ) { minNodeVal = root . key ; ans ++ ; } countReqNodes ( root . left , minNodeVal ) ; countReqNodes ( root . right , minNodeVal ) ; } public static void main ( String [ ] args ) { Node 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 ) ; int minNodeVal = Integer . MAX_VALUE ; ans = 0 ; countReqNodes ( root , minNodeVal ) ; System . out . print ( ans ) ; } }