Count nodes in a BST that falls within a given range

Posted on

// BST node

to classify Node

{

entire Data;

Node left, right;

Node(entire Data)

{

this.Data = Data;

this.left = this.right = bad;

}

}

to classify Major

{

// Recursive function to insert a given key into a BST

public static Node insert(Node root, entire key)

{

if (root == bad) {

come back New Node(key);

}

if (key < root.Data) {

root.left = insert(root.left, key);

}

other {

root.right = insert(root.right, key);

}

come back root;

}

// Function to count nodes in the BST that are within a given range

public static entire countNodes(Node root, entire down, entire high)

{

// base case

if (root == bad) {

come back 0;

}

// if the current node is in the current range, increment the count

// and reproduce for left and right subtrees

if (root.Data >= down && root.Data <= high)

{

come back 1 + countNodes(root.left, down, high) +

countNodes(root.right, down, high);

}

// repeat for the left subtree if the range is on its left subtree

if (root.Data > high) {

come back countNodes(root.left, down, high);

}

// repeat for the right subtree if the range is on its right subtree

if (root.Data < down) {

come back countNodes(root.right, down, high);

}

come back 0;

}

public static to cancel main(String of characters[] arguments)

{

// input range

entire down = 12, high = 20;

entire[] keys = { 15, 25, 20, 22, 30, 18, ten, 8, 9, 12, 6 };

// construct BST from above keys

Node root = bad;

for (entire key: keys) {

root = insert(root, key);

}

System.out.println(“The total number of nodes is “ +

countNodes(root, down, high));

}

}

Leave a Reply

Your email address will not be published.