Skip to content
Related Articles
Count the number of visible nodes in Binary Tree
• Difficulty Level : Easy
• Last Updated : 11 Nov, 2020

Given a Binary tree, the task is to find the number of visible nodes in the given binary tree. A node is a visible node if, in the path from the root to the node N, there is no node with greater value than N’s,
Examples:

```Input:
5
/  \
3     10
/  \   /
20   21 1

Output: 4
Explanation:
There are 4 visible nodes.
They are:
5: In the path 5 -> 3, 5 is the highest node value.
20: In the path 5 -> 3 -> 20, 20 is the highest node value.
21: In the path 5 -> 3 -> 21, 21 is the highest node value.
10: In the path 5 -> 10 -> 1, 10 is the highest node value.

Input:
-1
\
-2
\
-3
Output: 1

```

Approach: The idea is to first traverse the tree. Since we need to see the maximum value in the given path, the pre-order traversal is used to traverse the given binary tree. While traversing the tree, we need to keep the track of the maximum value of the node that we have seen so far. If the current node is greater or equal to the max value, then increment the count of the visible node and update the max value with the current node value.
Below is the implementation of the above approach:

## C++

 `// C++ implementation to``// count the number of``// visible nodes in the``// binary tree``#include ``using` `namespace` `std;` `// Node containing the``// left and right child of``// current node and the key value``struct` `Node``{``    ``int` `data;``    ``Node *left, *right;``};` `/* Utility that allocates a``new node with the given key and``NULL left and right pointers. */``struct` `Node* newnode(``int` `data)``{``    ``struct` `Node* node = ``new` `(``struct` `Node);``    ``node->data = data;``    ``node->left = node->right = NULL;``    ``return` `(node);``}` `// Variable to keep the track``// of visible nodes``int` `countNode = 0;` `// Function to perform the preorder traversal``// for the given tree``void` `preOrder(Node* node, ``int` `mx)``{``    ``// Base case``    ``if` `(node == NULL)``    ``{``        ``return``;``    ``}` `    ``// If the current node value is greater``    ``// or equal to the max value,``    ``// then update count variable``    ``// and also update max variable``    ``if` `(node->data >= mx)``    ``{``        ``countNode++;``        ``mx = max(node->data, mx);``    ``}` `    ``// Traverse to the left``    ``preOrder(node->left, mx);` `    ``// Traverse to the right``    ``preOrder(node->right, mx);``}` `// Driver code``int` `main()``{``    ``struct` `Node* root = newnode(5);` `    ``/*``            ``5``           ``/  \``         ``3     10``        ``/  \   /``       ``20   21 1``*/` `    ``root->left = newnode(3);``    ``root->right = newnode(10);``  ` `    ``root->left->left = newnode(20);``    ``root->left->right = newnode(21);` `    ``root->right->left = newnode(1);` `    ``preOrder(root, INT_MIN);` `    ``cout << countNode;``}` `// This code is contributed by gauravrajput1`

## Java

 `// Java implementation to count the``// number of visible nodes in``// the binary tree` `// Class containing the left and right``// child of current node and the``// key value``class` `Node {``    ``int` `data;``    ``Node left, right;` `    ``// Constructor of the class``    ``public` `Node(``int` `item)``    ``{``        ``data = item;``        ``left = right = ``null``;``    ``}``}` `public` `class` `GFG {``    ``Node root;` `    ``// Variable to keep the track``    ``// of visible nodes``    ``static` `int` `count;` `    ``// Function to perform the preorder traversal``    ``// for the given tree``    ``static` `void` `preOrder(Node node, ``int` `max)``    ``{` `        ``// Base case``        ``if` `(node == ``null``) {``            ``return``;``        ``}` `        ``// If the current node value is greater``        ``// or equal to the max value,``        ``// then update count variable``        ``// and also update max variable``        ``if` `(node.data >= max) {``            ``count++;``            ``max = Math.max(node.data, max);``        ``}` `        ``// Traverse to the left``        ``preOrder(node.left, max);` `        ``// Traverse to the right``        ``preOrder(node.right, max);``    ``}` `    ``// Driver code``    ``public` `static` `void` `main(String[] args)``    ``{``        ``GFG tree = ``new` `GFG();` `        ``/*``                ``5``               ``/  \``             ``3     10``            ``/  \   /``           ``20   21 1``*/` `        ``tree.root = ``new` `Node(``5``);``        ``tree.root.left = ``new` `Node(``3``);``        ``tree.root.right = ``new` `Node(``10``);` `        ``tree.root.left.left = ``new` `Node(``20``);``        ``tree.root.left.right = ``new` `Node(``21``);` `        ``tree.root.right.left = ``new` `Node(``1``);` `        ``count = ``0``;``        ``preOrder(tree.root, Integer.MIN_VALUE);` `        ``System.out.println(count);``    ``}``}`

## Python3

 `# Python 3 implementation to``# count the number of``# visible nodes in the``# binary tree` `import` `sys``# Node containing the``# left and right child of``# current node and the key value` `class` `newNode:``  ` `    ``def` `__init__(``self``, data):``      ` `        ``self``.data ``=` `data``        ``self``.left ``=` `None``        ``self``.right ``=` `None` `''' Utility that allocates a``new node with the given key and``None left and right pointers. */``'''` `# Variable to keep the track``# of visible nodes``countNode ``=` `0` `# Function to perform the``# preorder traversal for the``# given tree``def` `preOrder(node, mx):``  ` `    ``global` `countNode``    ` `    ``# Base case``    ``if` `(node ``=``=` `None``):``        ``return` `    ``# If the current node value``    ``# is greater or equal to the``    ``# max value, then update count``    ``# variable and also update max``    ``# variable``    ``if` `(node.data >``=` `mx):``        ``countNode ``+``=` `1``        ``mx ``=` `max``(node.data, mx)` `    ``# Traverse to the left``    ``preOrder(node.left, mx)` `    ``# Traverse to the right``    ``preOrder(node.right, mx)` `# Driver code``if` `__name__ ``=``=` `'__main__'``:``  ` `    ``root ``=` `newNode(``5``)` `    ``''' /*``            ``5``           ``/  \``         ``3     10``        ``/  /   /``       ``20   21 1``    ``*/``    ``'''``    ``root.left ``=` `newNode(``3``)``    ``root.right ``=` `newNode(``10``)``    ``root.left.left ``=` `newNode(``20``)``    ``root.left.right ``=` `newNode(``21``)``    ``root.right.left ``=` `newNode(``1``)``    ``preOrder(root, ``-``sys.maxsize``-``1``)``    ``print``(countNode)``    ` `# This code is contributed by SURENDRA_GANGWAR`

## C#

 `// C# implementation to count the``// number of visible nodes in``// the binary tree``using` `System;` `// Class containing the left and right``// child of current node and the``// key value``class` `Node``{``    ``public` `int` `data;``    ``public` `Node left, right;` `    ``// Constructor of the class``    ``public` `Node(``int` `item)``    ``{``        ``data = item;``        ``left = right = ``null``;``    ``}``}` `class` `GFG{``    ` `Node root;` `// Variable to keep the track``// of visible nodes``static` `int` `count;` `// Function to perform the preorder``// traversal for the given tree``static` `void` `preOrder(Node node, ``int` `max)``{` `    ``// Base case``    ``if` `(node == ``null``)``    ``{``        ``return``;``    ``}` `    ``// If the current node value is greater``    ``// or equal to the max value,``    ``// then update count variable``    ``// and also update max variable``    ``if` `(node.data >= max)``    ``{``        ``count++;``        ``max = Math.Max(node.data, max);``    ``}` `    ``// Traverse to the left``    ``preOrder(node.left, max);` `    ``// Traverse to the right``    ``preOrder(node.right, max);``}` `// Driver code``static` `public` `void` `Main(String[] args)``{``    ``GFG tree = ``new` `GFG();` `/*``         ``5``        ``/ \``      ``3       10``     ``/ \   /``    ``20 21 1``*/` `    ``tree.root = ``new` `Node(5);``    ``tree.root.left = ``new` `Node(3);``    ``tree.root.right = ``new` `Node(10);` `    ``tree.root.left.left = ``new` `Node(20);``    ``tree.root.left.right = ``new` `Node(21);``    ``tree.root.right.left = ``new` `Node(1);` `    ``count = 0;``    ``preOrder(tree.root, ``int``.MinValue);``    ``Console.WriteLine(count);``}``}` `// This code is contributed by Amit Katiyar`
Output:
```4

```

Complexity Analysis:
Time Complexity: O(N) where N is a number of nodes in the Binary tree.
Auxiliary Space: O(H) where H is the height of the Binary tree.

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with industry experts, please refer DSA Live Classes

My Personal Notes arrow_drop_up