0

So I'm trying to write a recursive function which return a "tail set" of an element in a BST. Basically, it returns every element that's greater than the input. Here's what I have so far.

  @Override
  public SortedSet<E> tailSet(E toElement){
      SortedSet<E> set = new SearchTreeSet<>();
      tailSet(root, toElement, set);
      return set;
    }

  private void tailSet(Node<E> n, E elt, SortedSet<E> set){
      if(n == null){
         return;
       }
      set.add((E) n.data);
      tailSet(n.left, elt, set);
      tailSet(n.right, elt, set);

  }

So this gets me the in-order output of the BST, but I'm unsure as how I need to use the toElement variable. toElement is the element in the set which I want to use as my base case, so everything that's greater will be put into the SortedSet set. I'm not sure how I need to go about doing this, any help will be greatly appreciated.

The constructors are defined by my professor so I cannot change them.

1 Answer 1

0

You just need to compare Element before adding it set , if current node data is less than toElement then return immediately . You can add this condition in your exisitng if condition of tailset()

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

3 Comments

How do I compare the data of the node to a generic type though?
see this link for compare generic types.
@paul If the answer helped you then select it as right answer.

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.