Count nodes having highest value in the path from root to itself in a Binary Tree

Given a Binary Tree, the task is to count the number of nodes in the Binary Tree, which are the highest valued node in the path from the root up to that node.
Examples:
Input: Below is the given Tree:
    3
    / \
   2  5
  /    \
 4     6
Output: 4
Explanation:
Root node satisfies the required condition.
Node 5 is the highest valued node in the path (3 -> 5).
Node 6 is the highest valued node in the path (3 -> 5 -> 6).
Node 4 is the highest valued node in the path (3 -> 2 -> 4).
Therefore, there are a total of 4 such nodes in the given binary tree.Input: Below is the given Tree:
     3
    / \
  1   2
  /    \
 4    6Â
Output: 3Â
Â
Approach: The idea is to perform Inorder Traversal of the given Binary Tree and update the maximum valued node obtained so far in the path after each recursive call. Follow the steps below:
- Perform Inorder Traversal on the given Binary Tree
- After each recursive call, update the maximum valued node encountered till now in the path from the root node to the current node.
- If the value of the node exceeds the maximum valued node in the path so far, increase the count by 1 and update the maximum value obtained so far.
- Proceed to the subtrees of the current node.
- After complete traversal of the Binary Tree, print the count obtained.
Below is the implementation of the above approach:
C++
// C++14 program for the above approach#include <bits/stdc++.h>using namespace std;Â
// Stores the ct of// nodes which are maximum// in the path from root// to the current nodeint ct = 0;Â
// Binary Tree Nodestruct Node {Â Â Â Â int val;Â Â Â Â Node *left, *right;Â Â Â Â Â Â Â Â Â Node(int x)Â Â Â Â {Â Â Â Â Â Â Â Â val = x;Â Â Â Â Â Â Â Â left = right = NULL;Â Â Â Â }};Â
// Function that performs Inorder// Traversal on the Binary Treevoid find(Node *root, int mx){         // If root does not exist    if (root == NULL)      return;         // Check if the node    // satisfies the condition    if (root->val >= mx)        ct++;         // Update the maximum value    // and recursively traverse    // left and right subtree    find(root->left, max(mx, root->val));         find(root->right, max(mx, root->val));}Â
// Function that counts the good// nodes in the given Binary Treeint NodesMaxInPath(Node* root){         // Perform inorder Traversal    find(root, INT_MIN);         // Return the final count    return ct;}Â
// Driver codeint main(){         /* A Binary Tree               3              / \             2  5            /    \           4      6         */    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);         // Function call    int answer = NodesMaxInPath(root);         // Print the count of good nodes    cout << (answer);    return 0;}Â
// This code is contributed by mohit kumar 29 |
Java
// Java program for the above approachimport java.util.*;Â
class GfG {Â
    // Stores the count of    // nodes which are maximum    // in the path from root    // to the current node    static int count = 0;Â
    // Binary Tree Node    static class Node {        int val;        Node left, right;    }Â
    // Function that performs Inorder    // Traversal on the Binary Tree    static void find(Node root, int max)    {        // If root does not exist        if (root == null)            return;Â
        // Check if the node        // satisfies the condition        if (root.val >= max)            count++;Â
        // Update the maximum value        // and recursively traverse        // left and right subtree        find(root.left,             Math.max(max, root.val));Â
        find(root.right,             Math.max(max, root.val));    }Â
    // Function that counts the good    // nodes in the given Binary Tree    static int NodesMaxInPath(Node root)    {        // Perform inorder Traversal        find(root, Integer.MIN_VALUE);Â
        // Return the final count        return count;    }Â
    // Function that add the new node    // in the Binary Tree    static Node newNode(int data)    {        Node temp = new Node();        temp.val = data;        temp.left = null;        temp.right = null;Â
        // Return the node        return temp;    }Â
    // Driver Code    public static void main(String[] args)    {        /* A Binary Tree              3             / \            2  5           /    \          4      6        */Â
        Node root = null;        root = newNode(3);        root.left = newNode(2);        root.right = newNode(5);        root.left.left = newNode(4);        root.right.right = newNode(7);Â
        // Function Call        int answer = NodesMaxInPath(root);Â
        // Print the count of good nodes        System.out.println(answer);    }} |
Python3
# Python 3 program for the # above approachimport sysÂ
# Stores the ct of# nodes which are maximum# in the path from root# to the current nodect = 0Â
# Binary Tree Nodeclass newNode:       def __init__(self, x):               self.val = x        self.left = None        self.right = NoneÂ
# Function that performs Inorder# Traversal on the Binary Treedef find(root, mx):       global ct         # If root does not exist    if (root == None):        return         # Check if the node    # satisfies the condition    if (root.val >= mx):        ct += 1         # Update the maximum value    # and recursively traverse    # left and right subtree    find(root.left,          max(mx, root.val))         find(root.right,          max(mx, root.val))Â
# Function that counts # the good nodes in the # given Binary Treedef NodesMaxInPath(root):       global ct         # Perform inorder     # Traversal    find(root,          -sys.maxsize-1)         # Return the final count    return ctÂ
# Driver codeif __name__ == '__main__':       '''     /* A Binary Tree               3              / /            2  5            /    /          4      6         */    '''    root = newNode(3)    root.left = newNode(2)    root.right = newNode(5)    root.left.left = newNode(4)    root.right.right = newNode(7)         # Function call    answer = NodesMaxInPath(root)         # Print the count of good nodes    print(answer)Â
# This code is contributed by Surendra_Gangwar |
C#
// C# program for // the above approachusing System;class GfG{Â
// Stores the count of// nodes which are maximum// in the path from root// to the current nodestatic int count = 0;Â
// Binary Tree Nodepublic class Node {Â Â public int val;Â Â public Node left, Â Â Â Â Â Â Â Â Â Â Â Â Â Â right;}Â
// Function that performs // Inorder Traversal on // the Binary Treestatic void find(Node root,                  int max){  // If root does not exist  if (root == null)    return;Â
  // Check if the node  // satisfies the condition  if (root.val >= max)    count++;Â
  // Update the maximum value  // and recursively traverse  // left and right subtree  find(root.left,  Math.Max(max, root.val));Â
  find(root.right,  Math.Max(max, root.val));}Â
    // Function that counts the good    // nodes in the given Binary Tree    static int NodesMaxInPath(Node root)    {        // Perform inorder Traversal        find(root, int.MinValue);Â
        // Return the readonly count        return count;    }Â
// Function that add the new node// in the Binary Treestatic Node newNode(int data){Â Â Node temp = new Node();Â Â temp.val = data;Â Â temp.left = null;Â Â temp.right = null;Â
  // Return the node  return temp;}Â
// Driver Codepublic static void Main(String[] args){  /* A Binary Tree              3             / \            2  5           /    \          4      6        */Â
  Node root = null;  root = newNode(3);  root.left = newNode(2);  root.right = newNode(5);  root.left.left = newNode(4);  root.right.right = newNode(7);Â
  // Function Call  int answer = NodesMaxInPath(root);Â
  // Print the count of good nodes  Console.WriteLine(answer);}}Â
// This code is contributed by Princi Singh |
Javascript
<script>Â
// Javascript program for the above approachÂ
// Stores the count of// nodes which are maximum// in the path from root// to the current nodelet count = 0;Â
// Binary Tree Nodeclass Node{Â Â Â Â constructor(data) Â Â Â Â {Â Â Â Â Â Â Â Â this.left = null;Â Â Â Â Â Â Â Â this.right = null;Â Â Â Â Â Â Â Â this.val = data;Â Â Â Â }}Â
// Function that add the new node// in the Binary Treefunction newNode(data){    let temp = new Node(data);         // Return the node    return temp;}Â
// Function that performs Inorder// Traversal on the Binary Treefunction find(root, max){         // If root does not exist    if (root == null)        return;         // Check if the node    // satisfies the condition    if (root.val >= max)        count++;         // Update the maximum value    // and recursively traverse    // left and right subtree    find(root.left, Math.max(max, root.val));         find(root.right, Math.max(max, root.val));}Â
// Function that counts the good// nodes in the given Binary Treefunction NodesMaxInPath(root){         // Perform inorder Traversal    find(root, Number.MIN_VALUE);         // Return the final count    return count;}Â
// Driver codeÂ
/* A Binary Tree     3    / \   2  5  /    \ 4      6*/Â
let root = null;root = newNode(3);root.left = newNode(2);root.right = newNode(5);root.left.left = newNode(4);root.right.right = newNode(7);Â
// Function Calllet answer = NodesMaxInPath(root);Â
// Print the count of good nodesdocument.write(answer);Â Â Â
// This code is contributed by suresh07Â
</script> |
4
Â
Time Complexity: O(N)
Auxiliary Space: O(1)
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!



