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.

Paul
  • 289
  • 2
  • 10

1 Answers1

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()

Sumit Rathi
  • 693
  • 8
  • 15