Count nodes having highest value in the path from root to itself in a Binary Tree | C ++ 14 program for the above approach ; Stores the ct 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 ; Driver code ; A Binary Tree 3 / \ 2 5 / \ 4 6 ; Function call ; Print the count of good nodes
#include <bits/stdc++.h> NEW_LINE using namespace std ; int ct = 0 ; struct Node { int val ; Node * left , * right ; Node ( int x ) { val = x ; left = right = NULL ; } } ; void find ( Node * root , int mx ) { if ( root == NULL ) return ; if ( root -> val >= mx ) ct ++ ; find ( root -> left , max ( mx , root -> val ) ) ; find ( root -> right , max ( mx , root -> val ) ) ; } int NodesMaxInPath ( Node * root ) { find ( root , INT_MIN ) ; return ct ; } int main ( ) { Node * root = new Node ( 3 ) ; root -> left = new Node ( 2 ) ; root -> right = new Node ( 5 ) ; root -> left -> left = new Node ( 4 ) ; root -> right -> right = new Node ( 7 ) ; int answer = NodesMaxInPath ( root ) ; cout << ( answer ) ; return 0 ; }