Date:

Share:

Count nodes in a BST that lies within a given range – Techie Delight

Related Articles

// BST Junction

status cross section

int data;

cross section left, right;

cross section(int data)

It.data = data;

It.left = It.right = blank;

status main

// A recursive function for inserting a given key into a BST

public static cross section Insert(cross section root, int key)

If (root == blank)

Return New cross section(key);

If (key < root.data)

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

Other

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

Return root;

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

public static int countNodes(cross section root, int low, int Tall)

// Basic case

If (root == blank)

Return 0;

// If the current node is in the current range, increase the count

// and repeats left and right sub-tree

If (root.data > = low && root.data <= Tall)

Return 1 + countNodes(root.left, low, Tall) +

countNodes(root.right, low, Tall);

// Repeats the left sub-tree if the range is on its left sub-tree

If (root.data > Tall)

Return countNodes(root.left, low, Tall);

// Repeats the right sub-tree if the range is on its right sub-tree

If (root.data < low)

Return countNodes(root.right, low, Tall);

Return 0;

public static void main(wire[] args)

// Input range

int low = 12, Tall = 20;

int[] Keys = 15, 25, 20, 22, 30, 18, 10, 8, 9, 12, 6 ;

// Build a BST from the keys above

cross section root = blank;

To (int key: Keys)

root = Insert(root, key);

editorial board.outside.println(“The total number of nodes is” +

countNodes(root, low, Tall));

Source

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Popular Articles