Count distinct element in a BST
Last Updated :
20 Oct, 2023
Given a binary search tree (BST), the task is to count the number of distinct elements present in it.
Examples:
Input:
5
/ \
3 7
/ \ / \
2 4 6 8
Output : 7
Explanation: The distinct elements in the above BST are {2, 3, 4, 5, 6, 7, 8}.
Input:
8
/ \
5 15
/ \ / \
5 7 12 20
Output: 6
Explanation: The distinct elements in the above BST are {5, 7, 8, 12, 15, 20}.
Count distinct elements in a BST using In-order Traversal
The idea is to perform an in-order traversal of the tree, and for each node we visit, we can check if it is distinct from the previously visited node. For this, we can maintain a variable to store the value of the previously visited node, and compare it with the value of the current node.
Below are the steps for the above approach:
- Perform an in-order traversal of the BST, and for each node visited, check if it is distinct from the previously visited node.
- For the first node visited, set the previously visited node value to the minimum possible value in the BST (which will be INT_MIN).
- If the current node value is different from the previously visited node value, increment the count of distinct elements by 1 and update the value of the previously visited node to the current node value.
- After the traversal is complete, return the count of distinct elements.
Below is the code for the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
Node *left, *right;
Node( int val)
{
data = val;
left = right = NULL;
}
};
int countDistinct(Node* root)
{
int count = 0;
int prev = INT_MIN;
if (root == NULL)
return 0;
while (root != NULL) {
if (root->left == NULL) {
if (root->data != prev) {
count++;
prev = root->data;
}
root = root->right;
}
else {
Node* curr = root->left;
while (curr->right != NULL
&& curr->right != root) {
curr = curr->right;
}
if (curr->right == NULL) {
curr->right = root;
root = root->left;
}
else {
if (root->data != prev) {
count++;
prev = root->data;
}
curr->right = NULL;
root = root->right;
}
}
}
return count;
}
int main()
{
Node* root = new Node(5);
root->left = new Node(3);
root->left->left = new Node(2);
root->left->right = new Node(4);
root->right = new Node(7);
root->right->left = new Node(6);
root->right->right = new Node(8);
int distinct = countDistinct(root);
cout << "Distinct elements in BST: " << distinct
<< endl;
return 0;
}
|
Java
import java.util.*;
class Node {
int data;
Node left, right;
Node( int val)
{
data = val;
left = right = null ;
}
}
class Main {
static int countDistinct(Node root)
{
int count = 0 ;
int prev = Integer.MIN_VALUE;
if (root == null )
return 0 ;
while (root != null ) {
if (root.left == null ) {
if (root.data != prev) {
count++;
prev = root.data;
}
root = root.right;
}
else {
Node curr = root.left;
while (curr.right != null
&& curr.right != root) {
curr = curr.right;
}
if (curr.right == null ) {
curr.right = root;
root = root.left;
}
else {
if (root.data != prev) {
count++;
prev = root.data;
}
curr.right = null ;
root = root.right;
}
}
}
return count;
}
public static void main(String[] args)
{
Node root = new Node( 5 );
root.left = new Node( 3 );
root.left.left = new Node( 2 );
root.left.right = new Node( 4 );
root.right = new Node( 7 );
root.right.left = new Node( 6 );
root.right.right = new Node( 8 );
int distinct = countDistinct(root);
System.out.println( "Distinct elements in BST: "
+ distinct);
}
}
|
Python3
class Node:
def __init__( self , val):
self .data = val
self .left = None
self .right = None
def countDistinct(root):
count = 0
prev = float ( '-inf' )
if root is None :
return 0
while root is not None :
if root.left is None :
if root.data ! = prev:
count + = 1
prev = root.data
root = root.right
else :
curr = root.left
while curr.right is not None and curr.right ! = root:
curr = curr.right
if curr.right is None :
curr.right = root
root = root.left
else :
if root.data ! = prev:
count + = 1
prev = root.data
curr.right = None
root = root.right
return count
if __name__ = = '__main__' :
root = Node( 5 )
root.left = Node( 3 )
root.left.left = Node( 2 )
root.left.right = Node( 4 )
root.right = Node( 7 )
root.right.left = Node( 6 )
root.right.right = Node( 8 )
distinct = countDistinct(root)
print ( "Distinct elements in BST:" , distinct)
|
C#
using System;
public class Node {
public int data;
public Node left, right;
public Node( int val)
{
data = val;
left = right = null ;
}
}
public class GFG {
static int CountDistinct(Node root)
{
int count = 0;
int prev = int .MinValue;
if (root == null )
return 0;
while (root != null ) {
if (root.left == null ) {
if (root.data != prev) {
count++;
prev = root.data;
}
root = root.right;
}
else {
Node curr = root.left;
while (curr.right != null
&& curr.right != root) {
curr = curr.right;
}
if (curr.right == null ) {
curr.right = root;
root = root.left;
}
else {
if (root.data != prev) {
count++;
prev = root.data;
}
curr.right = null ;
root = root.right;
}
}
}
return count;
}
static void Main()
{
Node root = new Node(5);
root.left = new Node(3);
root.left.left = new Node(2);
root.left.right = new Node(4);
root.right = new Node(7);
root.right.left = new Node(6);
root.right.right = new Node(8);
int distinct = CountDistinct(root);
Console.WriteLine( "Distinct elements in BST: "
+ distinct);
}
}
|
Javascript
class Node {
constructor(val) {
this .data = val;
this .left = null ;
this .right = null ;
}
}
function countDistinct(root) {
let count = 0;
let prev = -Infinity;
if (root === null )
return 0;
while (root !== null ) {
if (root.left === null ) {
if (root.data !== prev) {
count++;
prev = root.data;
}
root = root.right;
}
else {
let curr = root.left;
while (curr.right !== null
&& curr.right !== root) {
curr = curr.right;
}
if (curr.right === null ) {
curr.right = root;
root = root.left;
}
else {
if (root.data !== prev) {
count++;
prev = root.data;
}
curr.right = null ;
root = root.right;
}
}
}
return count;
}
function main() {
let root = new Node(5);
root.left = new Node(3);
root.left.left = new Node(2);
root.left.right = new Node(4);
root.right = new Node(7);
root.right.left = new Node(6);
root.right.right = new Node(8);
let distinct = countDistinct(root);
console.log( "Distinct elements in BST: " + distinct);
return 0;
}
main();
|
Output
Distinct elements in BST: 7
Time Complexity: O(n) Where n is the number of nodes in the BST.
Auxiliary Space: O(1)
Count distinct elements in a BST using Recursive in-order traversal
This approach is to do an in-order traversal of the given BST in a recursive manner and keep maintaining the previous node value traversed in order to check if the current one has already occurred or not. This can be possible since inorder traversal gives sorted order of values of the nodes.
Below is the code for the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
Node *left, *right;
Node( int val)
{
data = val;
left = right = NULL;
}
};
void countDistinctUtil(Node* root, int & count, int & prev)
{
if (root == NULL)
return ;
countDistinctUtil(root->left, count, prev);
if (root->data != prev) {
count++;
prev = root->data;
}
countDistinctUtil(root->right, count, prev);
}
int countDistinct(Node* root)
{
int count = 0;
int prev = INT_MIN;
countDistinctUtil(root, count, prev);
return count;
}
int main()
{
Node* root = new Node(5);
root->left = new Node(3);
root->left->left = new Node(2);
root->left->right = new Node(4);
root->right = new Node(7);
root->right->left = new Node(6);
root->right->right = new Node(8);
int distinct = countDistinct(root);
cout << "Distinct elements in BST: " << distinct
<< endl;
return 0;
}
|
Java
class Node {
int data;
Node left, right;
Node( int val)
{
data = val;
left = right = null ;
}
}
public class GFG {
static void countDistinctUtil(Node root, int [] count,
int [] prev)
{
if (root == null )
return ;
countDistinctUtil(root.left, count, prev);
if (root.data != prev[ 0 ]) {
count[ 0 ]++;
prev[ 0 ] = root.data;
}
countDistinctUtil(root.right, count, prev);
}
static int countDistinct(Node root)
{
int [] count = { 0 };
int [] prev = { Integer.MIN_VALUE };
countDistinctUtil(root, count, prev);
return count[ 0 ];
}
public static void main(String[] args)
{
Node root = new Node( 5 );
root.left = new Node( 3 );
root.left.left = new Node( 2 );
root.left.right = new Node( 4 );
root.right = new Node( 7 );
root.right.left = new Node( 6 );
root.right.right = new Node( 8 );
int distinct = countDistinct(root);
System.out.println( "Distinct elements in BST: "
+ distinct);
}
}
|
Python3
class Node:
def __init__( self , val):
self .data = val
self .left = None
self .right = None
def countDistinctUtil(root, count, prev):
if root is None :
return
countDistinctUtil(root.left, count, prev)
if root.data ! = prev[ 0 ]:
count[ 0 ] + = 1
prev[ 0 ] = root.data
countDistinctUtil(root.right, count, prev)
def countDistinct(root):
count = [ 0 ]
prev = [ float ( '-inf' )]
countDistinctUtil(root, count, prev)
return count[ 0 ]
if __name__ = = '__main__' :
root = Node( 5 )
root.left = Node( 3 )
root.left.left = Node( 2 )
root.left.right = Node( 4 )
root.right = Node( 7 )
root.right.left = Node( 6 )
root.right.right = Node( 8 )
distinct = countDistinct(root)
print ( "Distinct elements in BST:" , distinct)
|
C#
using System;
class Node {
public int data;
public Node left, right;
public Node( int val)
{
data = val;
left = right = null ;
}
}
public class GFG {
static void CountDistinctUtil(Node root, ref int count,
ref int prev)
{
if (root == null )
return ;
CountDistinctUtil(root.left, ref count, ref prev);
if (root.data != prev) {
count++;
prev = root.data;
}
CountDistinctUtil(root.right, ref count, ref prev);
}
static int CountDistinct(Node root)
{
int count = 0;
int prev = int .MinValue;
CountDistinctUtil(root, ref count, ref prev);
return count;
}
static void Main()
{
Node root = new Node(5);
root.left = new Node(3);
root.left.left = new Node(2);
root.left.right = new Node(4);
root.right = new Node(7);
root.right.left = new Node(6);
root.right.right = new Node(8);
int distinct = CountDistinct(root);
Console.WriteLine( "Distinct elements in BST: "
+ distinct);
}
}
|
Javascript
class Node {
constructor(val) {
this .data = val;
this .left = null ;
this .right = null ;
}
}
function countDistinct(root) {
let count = 0;
let prev = Number.MIN_SAFE_INTEGER;
function countDistinctUtil(node) {
if (node === null ) {
return ;
}
countDistinctUtil(node.left);
if (node.data !== prev) {
count++;
prev = node.data;
}
countDistinctUtil(node.right);
}
countDistinctUtil(root);
return count;
}
function main() {
const root = new Node(5);
root.left = new Node(3);
root.left.left = new Node(2);
root.left.right = new Node(4);
root.right = new Node(7);
root.right.left = new Node(6);
root.right.right = new Node(8);
const distinct = countDistinct(root);
console.log( "Distinct elements in BST: " + distinct);
}
main();
|
Output
Distinct elements in BST: 7
Time Complexity: O(n) Where n is the number of nodes in the BST.
Auxiliary Space: O(h) where h is the depth of the BST. This is due to recursion stack space.
Related Articles:
Share your thoughts in the comments
Please Login to comment...