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