Given the root of a Binary Search Tree containing n nodes, and two integers l and r, find the sum of all node values that lie within the inclusive range [l, r].
Output: 54 Explanation: The nodes in the given Tree that lies in the range [10, 22] are {12, 20, 22}. Therefore, the sum of nodes is 12 + 20 + 22 = 54.
[Approach] - Traverse the tree and check if node lies in range
The idea to traverse the tree recursively. For each node, if it lies within the range, then return the sum of left subtree, right subtree and current node. If its value is less than range, then return the value of right subtree, because all the nodes in its left subtree are less than than the range. Otherwise return the value of left subtree, because all the nodes in its right subtree are greater than the range.
Output
54
Time Complexity: O(n), where n is the number of nodes in tree. Auxiliary Space: O(h), whereh is the height of tree.