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 of all prime weight nodes between given nodes in the given Tree
- Count the nodes of the tree which make a pangram when concatenated with the sub-tree nodes
- Count the nodes in the given tree whose weight is even
- Count of nodes that are greater than Ancestors
- Count the nodes whose sum with X is a Fibonacci number
- Count greater nodes in AVL tree
- Count the nodes of the given tree whose weight has X as a factor
- Count all pairs of adjacent nodes whose XOR is an odd number
- Count the nodes in the given tree whose sum of digits of weight is odd
- Count of nodes having odd divisors in the given subtree for Q queries
- Count the number of nodes at given level in a tree using BFS.
- Count of Nodes whose both immediate children are its prime factors
- Count the nodes in the given tree whose weight is prime
- Count the nodes whose weight is a perfect square
- Count the nodes in the given tree whose weight is even parity
- Count Non-Leaf nodes in a Binary Tree
- Count the nodes in the given tree whose weight is a power of two
- Determine the count of Leaf nodes in an N-ary tree
- Find count of pair of nodes at even distance
- Count of nodes which are at a distance X from root and leaves