Given a Binary Search Tree (BST) of integer values and a range [low, high], return count of nodes where all the nodes under that node (or subtree rooted with that node) lie in the given range.
Input: 10 / \ 5 50 / / \ 1 40 100 Range: [5, 45] Output: 1 There is only 1 node whose subtree is in the given range. The node is 40 Input: 10 / \ 5 50 / / \ 1 40 100 Range: [1, 45] Output: 3 There are three nodes whose subtree is in the given range. The nodes are 1, 5 and 40
We strongly recommend you to minimize your browser and try this yourself first.
The idea is to traverse the given Binary Search Tree (BST) in bottom up manner. For every node, recur for its subtrees, if subtrees are in range and the nodes are also in range, then increment the count and return true (to tell the parent about its status). The count is passed as a pointer so that it can be incremented across all function calls.
Below is implementation of the above idea.
Count of subtrees in [5, 45] is 1
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 nodes that lie in a given range
- 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
- Convert a normal BST to Balanced BST
- Two nodes of a BST are swapped, correct the BST | Set-2
- Two nodes of a BST are swapped, correct the BST
- Find k-th smallest element in BST (Order Statistics in 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
- Count permutations of given array that generates the same Binary Search Tree (BST)
- Count inversions in an array | Set 2 (Using Self-Balancing BST)
- Count of pairs violating BST property
- Find the largest BST subtree in a given Binary Tree | Set 1
- Sorted order printing of a given array that represents a BST
- Construct BST from given preorder traversal | Set 2
- Find a pair with given sum in a Balanced BST
- Add all greater values to every node in a given BST
- Construct BST from its given level order traversal