2

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:

  1. 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".

7
  • @John Kugelman: Did you move spaces around the critical point? Unless you have an alternate source that would be better left to the OP. Commented Sep 20, 2010 at 22:33
  • @Inverse, which layout comes closest? Commented Sep 20, 2010 at 22:43
  • The spacing around "10" in the example is provided as is from the given document. If it IS a typo...it's from whoever wrote the problem originally. I'm keeping the spacing as provided. Commented Sep 20, 2010 at 22:49
  • I think you're conflating two things. Your method of construction will give you ordinary binary search trees. However, your brief is to find an element in a tree with the given properties. In this case you can turn any permutation of the items in the tree into another tree satisfying the constraints. This means you can do no better than searching the entire tree. Commented Sep 20, 2010 at 23:58
  • @Rafe: I'm not sure I follow. The example is implicitly part of the specification. The typo on the placement of the 10 meant this WASN'T a BST. I don't recall mentioning any kind of brief, or any requirement to find an element with given properties. The alorithms I'm looking for are insertion and traversal. I will agree that the only efficient way to do traversal, with a non-BST like this, is to introduce a second data-structure. Commented Sep 21, 2010 at 22:46

2 Answers 2

3

Te examples makes sense until the 10 appears. Basic assumption: It's a typo. But it can't (and doesn't look to) be a child of 5. It is the left child of 9.

But it's also the first that would require restructuring the Tree (to fit it between 9 and 12). To me it looks like the last picture is half-way such a restructuring. Are we seeing the end of the story?

Edit

Ok, I didn't read rule 2 completely. It looks like 10 should have become the left-child of 12. There is no good reason for the Insert to take a left branch at the root.

If 10 is the child of either 5 or 9, it stops being a BST or anything else but an unordered binary tree.

Sign up to request clarification or add additional context in comments.

3 Comments

What's wrong with the 10? It can very well be a right child of 5: 3 <= 5 <= 10. Looks fine to me.
It can't be the left child of 9, since 10 > 9, not less. And yes, this is the end of the story. No restructuring this kind of tree. Insertions ALWAYS create a new leaf node, and no switching of values is permitted.
@Henk's edit - Right...I blew away most of my testing time under the assumption this was a BST. Once I looked closer...I couldn't really make much of it. Insertion becomes nasty, and traversal requires another data-structure else it becomes grossly inefficient.
1

Edit

On second thought, I am more inclined to believe there's a typo in your example than this is not intended to be a BST. The location of the 10 doesn't make sense. Up until then it is a perfectly valid BST. If the 10 were inserted as the left leaf of the 12 node instead then the BST-ness would be preserved.

If leftNode.value < value <= rightNode.value only applies to immediate children and not to all descendants then this is a useless data structure. I mean I guess it's usable, but since you'll end up traversing the entire tree on both inserts and lookups it seems rather pointless.


I imagine the outline of your insertion algorithm will look like the following pseudo-Python. The gist of it is to try adding the node as a leaf where possible, or inserting it on either sub-tree. Left or right, it doesn't matter.

Basically we're just looking down the entire tree for anywhere the new value can be added as a leaf node. As you say, the ordering criterion only applies to immediate children. You have to be picky about adding new leaf nodes. But you will try both left and right sub-trees indiscriminately.

class TreeNode:
    def insert(self, value):
        # Can we add it as the left leaf of this node?
        if self.left is None and value < self.value:
            self.left = TreeNode(value)
            return True

        # Can we add it as the right leaf of this node?
        if self.right is None and value >= self.value:
            self.right = TreeNode(value)
            return True

        # Can we add it somewhere down the left sub-tree?
        if self.left.insert(value):
            return True

        # Can we add it somewhere down the right sub-tree?
        if self.right.insert(value):
            return True

        # Didn't find anywhere to add the node.
        return False

I guess where it becomes tricky is if you have to attempt to balance the sub-trees and not just haphazardly insert new nodes at any arbitrary point in the tree. If that's an issue, then you could amend the above algorithm to insert at the shallowest point possible.

Pretend there is a insert_depth method which returns the depth a node would be inserted at if it were inserted down a particular sub-tree, or returns ∞ if insertion is impossible. Again, this is just pseudo-code:

left_depth  = self.left .insert_depth(value)
right_depth = self.right.insert_depth(value)

if left_depth < right_depth:
    return self.left .insert(value)
else:
    return self.right.insert(value)

In real code I'd write an "if you were going to insert a node, where would you insert it?" helper method. Run that method on both sub-trees, compare the insertion points, and pick one (i.e. the shallowest). The code would be a bit awkward but it would save you from traversing each sub-tree twice.

1 Comment

That was my original thought, but according to your algorithm, once you start down the left node, (if it doesn't find a place to insert beforehand) it will encounter a leaf, and will ALWAYS be set as a left or right child. Your right subtree insert will never be reached. From the example above, the insertion of 12, if following your algorithm, would have placed it as the right child of 5.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.