Count nodes having smallest value in the path from root to itself in a Binary Tree | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int key ; Node * left , * right ; } ; Node * newNode ( int key ) { Node * temp = new Node ; temp -> key = key ; temp -> left = temp -> right = NULL ; return temp ; } void countReqNodes ( Node * root , int minNodeVal , int & ans ) { if ( root == NULL ) return ; if ( root -> key <= minNodeVal ) { minNodeVal = root -> key ; ans ++ ; } countReqNodes ( root -> left , minNodeVal , ans ) ; countReqNodes ( root -> right , minNodeVal , ans ) ; } int main ( ) { 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 ans = 0 , minNodeVal = INT_MAX ; countReqNodes ( root , minNodeVal , ans ) ; cout << ans ; return 0 ; }