February 24, 2025 |290 Views

Count BST nodes that lie in a given range

Explore Courseexplore course icon
Description
Discussion

In this video, we will discuss two approaches to count the number of nodes in a Binary Search Tree (BST) that lie within a given range [l, h]. The first approach uses recursion, where we traverse the tree starting from the root. At each node, we check if the node’s value is within the range. If it is, we increment the count and recursively check the left and right subtrees. If the node’s value is less than the lower bound, we only recurse on the right subtree, and if it’s greater than the upper bound, we recurse on the left subtree. This method runs in O(n) time, where n is the number of nodes in the tree, and uses O(h) space, where h is the height of the tree due to recursive function calls.

The second approach uses a queue and performs a level-order traversal (BFS). We check each node to see if its value is within the given range. If it is, we increment the count and push its left and right children into the queue. If the node’s value is less than the lower bound, we only push the right child, and if it’s greater than the upper bound, we only push the left child. This approach also runs in O(n) time but uses O(n) space due to the queue storing the nodes during the traversal. Watch the video to understand both methods in detail and learn how to efficiently count nodes within a range in a BST.

For more details, please go through - Count BST nodes that lie in a given range