Two sum in BST
A BST's inorder is sorted, so the two-pointer method for a sorted array works directly on it: one iterator walks up from the smallest value, another walks down from the largest. Move the small end up when the sum is too small and the big end down when it is too large. With two different BSTs, run one ascending and one descending.
How to recognise it
- A pair of values in a BST (or two BSTs) with a given sum.
- Sorted order is available, and O(h) memory is wanted.
- The array version would use two pointers.
Two pointers on a tree
lo = forward iterator; hi = backward iterator
while lo.node is not hi.node:
s = lo.val + hi.val
if s == k: found
if s < k: lo.next() else: hi.prev()
The rule that makes a BST, and how it compares with a heap, is on the Structures page.
Two trees
For pairs (a from the first BST, b from the second) with a + b = x, walk the first ascending and the second
descending. Count a match and move both; otherwise move the side that brings the sum closer.
Common mistakes
- Pairing a node with itself.
- Using a hash set of all values, which works but needs O(n) memory.
Problems
- Two Sum IV - Input is a BSTeasyguide ready
- Count pairs from 2 BST whose sum is equal to given value "X"mediumguide ready