The recursive version came naturally, prune left if the current node is below the low bound, prune right if it's above the high, otherwise recurse both sides and accumulate.
Start by clarifying the problem and edge cases, then explain how BST properties allow pruning subtrees outside the range. Present both recursive and iterative solutions, emphasizing the pruning logic, and analyze time and space complexity for each.
Pro tip: Mention that the iterative solution can use an explicit stack to simulate recursion, but avoid extra space by using a Morris-like traversal or by pruning with a stack that only stores necessary nodes. Also, note that the time complexity is O(h + k) where h is height and k is number of nodes in range, but worst-case O(n) for skewed trees.
Restate the problem: sum all node values in a BST within inclusive bounds [low, high]. Discuss edge cases: empty tree, low > high, bounds outside tree range.
Write a recursive function that checks if current node value is within range; if so, add to sum. Recurse left only if node.val > low, and right only if node.val < high, leveraging BST order to prune.
Use an explicit stack to simulate recursion. Push root, then while stack not empty, pop node; if node.val in range, add to sum and push both children; else if node.val < low, push right child; else push left child. This prunes branches.
For both: Time O(n) worst-case (skewed tree), but O(h + k) average where h is height and k is nodes in range. Space: Recursive O(h) due to call stack; Iterative O(h) for stack in worst-case, but can be O(k) if pruning effectively.
Discuss trade-offs: recursion is cleaner but risks stack overflow for deep trees; iteration avoids recursion overhead but may use explicit stack. Both leverage BST properties for efficiency.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.