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 in a given Range
- Print BST keys in the given range
- Remove BST keys outside the given range
- Print BST keys in given Range | O(1) Space
- Count greater nodes in AVL tree
- Count of pairs violating BST property
- Count pairs from two BSTs whose sum is equal to a given value x
- Count inversions in an array | Set 2 (Using Self-Balancing BST)
- Find maximum count of duplicate nodes in a Binary Search Tree
- Count the Number of Binary Search Trees present in a Binary Tree
- Check if a Binary Tree is BST : Simple and Efficient Approach
- Difference between Binary Tree and Binary Search Tree
- Maximum height of the binary search tree created from the given array