VOOZH about

URL: https://www.geeksforgeeks.org/dsa/count-the-unique-type-of-nodes-present-in-binary-tree/

⇱ Count the unique type of nodes present in Binary tree - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Count the unique type of nodes present in Binary tree

Last Updated : 23 Jul, 2025

According to the property of a Binary tree, a node can have at most two children so there are three cases where a node can have two children, onechild, or no child, the task is to track the count of unique nodes and return the total number of unique nodes that have no child, one child, and two children. Given the root of the binary tree return a vector where arr[0] represents the total unique nodes that contain 0 children, arr[1] represents the total unique nodes having 1 child, and arr[2] represents the total unique nodes that have exactly two children.

Examples:

Input:

2
/ \
1 4
/ \ \
2 1 1
/ \
7 5

Output: 4 1 2
Explanation: Nodes with no child are 2, 1, 7, and 5 and all these nodes have unique values so the count is 4. There is only 1 Node with 1 child i.e. 4 so the count will be 1 here.
Nodes with two children are 2 (root), 1 ( 2's child ), and 1 ( 4's child ), since 1 is repeating that's why only 2 (root) and 1 will be counted as unique nodes so the count will be 2 here.

Input:

3
/ \
2 2

Output: 1 0 1
Explanation: Nodes with no child are 2 and 2 so the unique node's count will be 1.
There is no node with 1 child so the count will be 0.
There is only 1 node with 2 children i.e. 3 (root node) so the count will be 1 here.

Approach: To solve the problem follow the below idea:

We can consider the different types of nodes as a pattern and use a hashmap to store every unique node's pattern.

Follow the steps to solve the problem:

  • We can use three hashmaps for three patterns i.e. node with two children, node with one child, node with no child, and traverse over the tree and match the current node's pattern if the current node's value is unique then store it in the hashmap.
  • After completing the entire traversal return the size of all three hashmaps which represent all three patterns. For storing data in hashmaps pass the hashmap by reference.

Below code is the implementation of the above approach:


Output
4 1 2

Time Complexity: O(N*logN), N For traversing the tree and LogN for map operations
Auxiliary Space: O(N), For hashmaps, at max, N values can be stored

Comment
Article Tags: