[Expected Approach] Using Recursion - O(n) Time and O(h) Space
The idea is traverse the given binary search tree starting from root. For every node check if this node lies in range, if yes, then add 1 to result and recursively check for both of its children. If current node is smaller than low value of range, then recur for right child, else recur for left child.
Follow the below steps to Implement the idea:
Traverse the tree starting from the root.
If root->data is equal to high and root->data is equal to low return 1.
If root->data <= high and root->data >= low then return 1 + count on left of root + count on right of root.
Else if root->data < low return count on right of root.
Else if root->data > high return count on left of root.
Below is the implementation of the above approach.
Output
3
[Alternate Approach] Using Queue - O(n) Time and O(n) Space
The idea is traverse the given binary search tree in level order manner using a queue. For every node check if this node lies in range, if yes, then add 1 to result and push both of its children into queue. If current node is smaller than low value of range, then push right child, else push left child.
Below is the implementation of the above approach: