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.
- Count BST subtrees that lie in given range
- Two nodes of a BST are swapped, correct the BST | Set-2
- Two nodes of a BST are swapped, correct the BST
- Remove all nodes which don't lie in any path with sum>= k
- Find pairs with given sum such that pair elements lie in different BSTs
- K'th Largest Element in BST when modification to BST is not allowed
- Find k-th smallest element in BST (Order Statistics in BST)
- Convert a normal BST to Balanced BST
- Count of all prime weight nodes between given nodes in the given Tree
- Sum of cousin nodes of a given node in a BST
- Print BST keys in the given range
- Remove BST keys outside the given range
- Print BST keys in given Range | O(1) Space
- Remove BST Keys in a given Range
- Maximum element between two nodes of BST
- Shortest distance between two nodes in BST
- Implementing a BST where every node stores the maximum number of nodes in the path till any leaf
- Count permutations of given array that generates the same Binary Search Tree (BST)
- Count the nodes of the tree which make a pangram when concatenated with the sub-tree nodes
- Sum of all odd nodes in the path connecting two given nodes