Given a Binary Search Tree (BST) and a range, count number of nodes that lie in the given range.
Input: 10 / \ 5 50 / / \ 1 40 100 Range: [5, 45] Output: 3 There are three nodes in range, 5, 10 and 40
The idea is to traverse the given binary search tree starting from root. For every node being visited, check if this node lies in range, if yes, then add 1 to result and recur for both of its children. If current node is smaller than low value of range, then recur for right child, else recur for left child.
Below is the implementation of above idea.
Count of nodes between [5, 45] is 3
Time complexity of the above program is O(h + k) where h is height of BST and k is number of nodes in given range.
This article is contributed by Gaurav Ahirwar. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Remove all nodes which don't lie in any path with sum>= k
- Count of all prime weight nodes between given nodes in the given Tree
- Find k-th smallest element in BST (Order Statistics in BST)
- K'th Largest Element in BST when modification to BST is not allowed
- Convert a normal BST to Balanced BST
- Print BST keys in the given range
- Implementing a BST where every node stores the maximum number of nodes in the path till any leaf
- Count the nodes of the tree which make a pangram when concatenated with the sub-tree nodes
- Count permutations of given array that generates the same Binary Search Tree (BST)
- Sum of all odd nodes in the path connecting two given nodes
- Common nodes in the inorder sequence of a tree between given two nodes in O(1) space
- Count pairs in BST with sum greater than K
- Print levels with odd number of nodes and even number of nodes
- Minimum number of Nodes to be removed such that no subtree has more than K nodes
- Find the largest BST subtree in a given Binary Tree | Set 1
- Construct BST from given preorder traversal | Set 2
- Add all greater values to every node in a given BST
- Inorder predecessor and successor for a given key in BST
- Construct BST from its given level order traversal
- Check given array of size n can represent BST of n levels or not