views:

328

answers:

2

Can anyone point me to a code example (java preferably) or psuedocode that uses recursion to return a subtree that contains all nodes with keys between fromKey and toKey.

So if I was to call Tree.subtree(5,10) it should return all nodes in the BST that have keys between 5 and 10 inclusive - but I can't use loops or helper methods...only recursive calls to the subtree method, which takes fromKey and toKey as parameters.

Thanks!

Update:

I've try the following which does not work:

public Tree subtree(int from, int to) {
   left.subtree(from, to);
   right.subtree(from, to);
   if (this.key < from || this.key > to) {
      this.delete(this.key);
   }
   return this;   
}

I think the problem with this is that it returns too early. What I'm trying to do is traverse every node on the tree, and delete any that don't fall within the range. Am I on the right track?

+1  A: 

You're supposed to do the homework. Then when you get stuck, ask questions. Sounds like you're asking us to do your homework for you.

Shakedown
I've done the recursive delete, insert, min, max, size, etc...Stuck on the subtree - I've definitely tried a bunch of failed implementations, should I post them??
Art Peterson
@peterson, surely yes
TiansHUo
Ok posted my attempt above
Art Peterson
This non-answer (which somehow acquired scoring upvotes) should've been a comment.
polygenelubricants
+2  A: 

Shouldn't the subtree return a copy of the original tree, instead of removing keys from it? And how does your original recursion terminate?

I would recommend something like this:

public static Tree subtreeNullSafe(Tree t, int from, int to) {
   return t == null ? null : t.subtree(from, to);
}

public Tree subtree(int from, int to) {
   if (this.key > to) {
     return subtreeNullSafe(this.left, from, to);
   } else if (this.key < from) {
     return subtreeNullSafe(this.right, from, to);
   } else {
     // we know that this.key <= to and this.key >= from
     return new Tree(
       this.key,
       subtreeNullSafe(this.left, from, to),
       subtreeNullSafe(this.right, from, to)
     );
   }
}

This does use a helper method to reduce repetition. You can just inline the null check if you're really forbidden from using even that.

polygenelubricants
Thanks so much! I didn't have my constructor set up to take left and right tree parameter - as soon as I saw that in your solution it clicked.
Art Peterson