Ok, I ran into this tree question which LOOKED simple, but started driving me nuts.
The tree given is LIKE a binary search tree, but with one difference:
- For a Node, leftNode.value < value <= rightNode.value. However, (by their omission of any further info, and by their example below) this ONLY applies to the immediate children, not the nodes beneath each child. So it's possible to have a value somewhere in the left subtree that is >= the current node's value.
This is NOT a self-balancing tree; the existing tree structure will not be changed on an insert, aside from adding the new value in a new leaf node. No switches or shifts of values or nodes allowed.
Also given was an example of the tree structure after test values were inserted:
If we insert 8, 5, 9, 3, 3, 2, 12, 4, 10:
8
8
5
8
5 9
8
5 9
3
8
5 9
3
3
8
5 9
3
2 3
8
5 9
3 12
2 3
8
5 9
3 12
2 3
4
8
5 9
3 10 12
2 3
4
I assumed the 10 was the right child of 5, since the given constraint prevents it from being the left child of 9.
My requirements, given the rule above for nodes and the example of expected tree structure and behavior for given input: write a traversal and insertion algorithm for this tree.
Since this isn't a real BST and we're not allowed to alter the tree, I couldn't think of any clever way to perform traversal, other than using another data-structure to get this in order.
I've got an insertion algorithm which might work, but since it would have to allow back ups to the parent node and exploration of the other path (in both cases where it starts traveling down the left or the right), it would be a really funky looking algorithm.
This question was placed alongside normal, basic programming questions, so it seemed a little out of place. So...any insights here? Or am I overlooking something obvious?
EDIT: Problem solved. It WAS a typo introduced by the test-giver. This was meant to be a BST, but the "10" in the example was placed in the wrong position; it should have been the left child of "12".