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.
- Count the nodes of the tree which make a pangram when concatenated with the sub-tree nodes
- Count greater nodes in AVL tree
- Count the nodes in the given tree whose weight is even
- Count the nodes whose sum with X is a Fibonacci number
- Count the nodes in the given tree whose sum of digits of weight is odd
- Count all pairs of adjacent nodes whose XOR is an odd number
- Count of nodes which are at a distance X from root and leaves
- Count the nodes of the given tree whose weight has X as a factor
- Count Non-Leaf nodes in a Binary Tree
- Count the nodes whose weight is a perfect square
- Determine the count of Leaf nodes in an N-ary tree
- Count the number of nodes at given level in a tree using BFS.
- Count the nodes in the given tree whose weight is prime
- Count the nodes in the given tree whose weight is a power of two
- Count the nodes in the given tree whose weight is even parity