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 is also in range, then increment count and return true (to tell the parent about its status). 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.
- Count BST nodes that lie in a given range
- Remove BST keys outside the given range
- Remove BST Keys in a given Range
- Print BST keys in the given range
- Print BST keys in given Range | O(1) Space
- Count of pairs violating BST property
- Count greater nodes in AVL tree
- Count inversions in an array | Set 2 (Using Self-Balancing BST)
- Count pairs from two BSTs whose sum is equal to a given value x
- Find maximum count of duplicate nodes in a Binary Search Tree
- Count the Number of Binary Search Trees present in a Binary Tree
- Total number of BSTs using array elements
- Duplicates Removal in Array using BST
- Median of sliding window in an array