This is not homework, this is an interview question.
The catch here is that the algorithm should be constant space. I'm pretty clueless on how to do this without a stack, I'd post what I've written using a stack, but it's not relevant anyway.
Here's what I've tried: I attempted to do a pre-order traversal and I got to the left-most node, but I'm stuck there. I don't know how to "recurse" back up without a stack/parent pointer.
Any help would be appreciated.
(I'm tagging it as Java since that's what I'm comfortable using, but it's pretty language agnostic as is apparent.)
It's a binary search tree, so every node can be reached by a series of right/left decision. Describe that series as 0/1, least-significant bit to most-significant. So the function f(0) means "the node found by taking the right-hand branch until you find a leaf; f(1) means take one left and the rest right; f(2) -- that is, binary 010 -- means take a right, then a left, then rights until you find a leaf. Iterate f(n) starting at n=0 until you have hit every leaf. Not efficient (since you have to start at the top of the tree each time) but constant memory and linear time.
The title of the question doesn't mention the lack of a "parent" pointer in the node. Although it isn't necessarily required for BST, many binary tree implementations do have a parent pointer. class Node { Node* left; Node* right; Node* parent; DATA data; };
It this is the case, imaging a diagram of the tree on paper, and draw with a pencil around the tree, going up and down, from both sides of the edges (when going down, you'll be left of the edge, and when going up, you'll be on the right side). Basically, there are 4 states:
minor special case for iluxa's answer above
Here's a shorter version iluxa's original answer. It runs exactly the same node manipulation and printing steps, in exactly the same order — but in a simplified manner [1]:
[1] Plus, it even works when the tree root node has no left child.
Accepted answer needs the following change otherwise it will not print the tree where the BST only has one node
It's a a search tree, so you can always get the next key/entry
You need smth like (I didn't test the code, but it's as simple as it gets)
for clarity this is
higherEntry
, so it's not recursive. There you have it :)