Sponsored
Sponsored
This approach involves performing a recursive in-order traversal to accumulate the sum of nodes within the given value range.
Because of the BST properties, the in-order traversal naturally allows visiting nodes in a sorted order, which means that once the current node value is larger than 'high', you can stop traversing further right subtree. Similarly, if the current node value is smaller than 'low', you can avoid traversing the left subtree further.
Time Complexity: O(N), where N is the number of nodes in the tree since in the worst case we must visit all nodes.
Space Complexity: O(H), where H is the height of the tree (accounting for the recursion stack).
1
2class TreeNode:
3 def __init__(self, val=0, left=None, right=None):
4 self.val = val
5 self.left = left
6 self.right = right
7
8class Solution:
9 def rangeSumBST(self, root: TreeNode, low: int, high: int) -> int:
10 if not root:
11 return 0
12 if root.val < low:
13 return self.rangeSumBST(root.right, low, high)
14 if root.val > high:
15 return self.rangeSumBST(root.left, low, high)
16 return root.val + self.rangeSumBST(root.left, low, high) + self.rangeSumBST(root.right, low, high)
17
The Python solution involves recursive function calls, leveraging Python's concise syntax to implement the in-order traversal logic with minimal code.
This approach uses an iterative method with an explicit stack to facilitate an in-order traversal. Utilizing a stack allows avoiding the function call stack and can handle larger trees without risking stack overflow in languages with limitations on recursion depth.
As we push nodes onto the stack, we continue to the leftmost node, then process nodes and move to the right, ensuring nodes are visited in non-decreasing order. Only nodes within the range are added to the sum.
Time Complexity: O(N) where N is the number of nodes.
Space Complexity: O(H) where H is the height of the tree due to the stack usage.
This Java approach uses an explicit stack to avoid recursion. It effectively traverses the tree, maintaining an order that respects the in-order traversal.