Try as I could, I'm not sure this is possible with a binary tree that has no parent pointers. O(1)
space means you can neither use recursion (the stack growth is O(log n)
) nor copying to a doubly linked list (O(n)
).
The method you allude to is an O(n)
time complexity solution but not with a normal binary tree. In fact, I answered a similar question in great detail here. That was solved with O(n)
space but only because they weren't initially sorted.
It is possible with a tree containing parent pointers. If the child nodes have pointers to their parents, you can basically treat the tree as a doubly-linked list processed iteratively.
To do that, you run the start pointer down to the leftmost node and the end pointer down to the righmost node. You also maintain two variables to store the last movement (up or across, initially up) of each pointer so you can intelligently select the next move (the front++
and end--
in your question).
Then you can use the current pointers and last movements, along with the current sum, to decide which pointer to move (and how).