Count nodes having highest value in the path from root to itself in a Binary Tree | Java program for the above approach ; Stores the count of nodes which are maximum in the path from root to the current node ; Binary Tree Node ; Function that performs Inorder Traversal on the Binary Tree ; If root does not exist ; Check if the node satisfies the condition ; Update the maximum value and recursively traverse left and right subtree ; Function that counts the good nodes in the given Binary Tree ; Perform inorder Traversal ; Return the final count ; Function that add the new node in the Binary Tree ; Return the node ; Driver Code ; A Binary Tree 3 / \ 2 5 / \ 4 6 ; Function Call ; Print the count of good nodes
import java . util . * ; class GfG { static int count = 0 ; static class Node { int val ; Node left , right ; } static void find ( Node root , int max ) { if ( root == null ) return ; if ( root . val >= max ) count ++ ; find ( root . left , Math . max ( max , root . val ) ) ; find ( root . right , Math . max ( max , root . val ) ) ; } static int NodesMaxInPath ( Node root ) { find ( root , Integer . MIN_VALUE ) ; return count ; } static Node newNode ( int data ) { Node temp = new Node ( ) ; temp . val = data ; temp . left = null ; temp . right = null ; return temp ; } public static void main ( String [ ] args ) { Node root = null ; root = newNode ( 3 ) ; root . left = newNode ( 2 ) ; root . right = newNode ( 5 ) ; root . left . left = newNode ( 4 ) ; root . right . right = newNode ( 7 ) ; int answer = NodesMaxInPath ( root ) ; System . out . println ( answer ) ; } }