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.
- Print BST keys in the given range
- Remove BST keys outside the given range
- Count inversions in an array | Set 2 (Using Self-Balancing BST)
- Count BST nodes that lie in a given range
- Count pairs from two BSTs whose sum is equal to a given value x
- Count greater nodes in AVL tree
- Print BST keys in given Range | O(1) Space
- Remove BST Keys in a given Range
- Count of pairs violating BST property
- Count the Number of Binary Search Trees present in a Binary Tree
- Red-Black Trees | Top-Down Insertion
- Implementing a BST where every node stores the maximum number of nodes in the path till any leaf
- Pre-Order Successor of all nodes in Binary Search Tree
- Lexicographically Smallest Topological Ordering