binary search tree recursive subtree in java
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 &l开发者_JAVA技巧t; 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?
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.
精彩评论