I think jonderry is very close, but parent pointers require \ Omega (n) memory, that is, they significantly affect memory usage. What he does is two coordinated transitions in opposite directions (from small to large and viveversa), which try to keep the amount always close to the target, and you can handle these two stacks, and the stacks can only grow to the depth of the tree and this is O (log n). I do not know if there is this βsmallβ additional memory, but, of course, it is less than additional memory and o (n). Thus, this is exactly the same as in jonderry's own comment, but there is no penalty for execution, because moving the binary tree using only the stack is a well-known and efficient and definitely O (n) operation. Thus, you increase the iterator ii and decrease the iterator di.
x = ii.next() y = di.next() while (true) { try: if x + y > target {y = di.next()} if x + y < target {x = ii.next()} if x + y == target {return (x,y)} except IterError: break } return None
I ran into the same problem in the context of calculating pseudo-media, the median of all pairwise averages in the sample.
source share