title: How to print out the nth most frequent words in a binary search tree?
body: <p>This concerns "a software algorithm" <a href="https://stackoverflow.com/help/on-topic">https://stackoverflow.com/help/on-topic</a></p>
  
  <p>I am currently writing a word counter dictionary program. To store the different word counts, I am using a Binary Search Three with the word as the key and the frequency as the value.</p>
  
  <p>Here is my Binary Search Tree class </p>
  
  <pre><code>public class BinarySearchTree&lt;AnyKey extends Comparable&lt;? super AnyKey&gt;, AnyValue&gt;
      implements MyTreeMap&lt;AnyKey, AnyValue&gt;{
                protected BinaryNode&lt;AnyKey, AnyValue&gt; root;
                protected BinaryNode&lt;AnyKey, AnyValue&gt; insert(AnyKey x, 
                        AnyValue y, BinaryNode&lt;AnyKey, AnyValue&gt; t ){
                      if( t == null )
                           t = new BinaryNode&lt;AnyKey, AnyValue&gt;(x, y );
                     else if( x.compareTo( t.element ) &lt; 0 )
                           t.left = insert( x, y, t.left );
                    else if( x.compareTo( t.element ) &gt; 0 )
                          t.right = insert( x, y, t.right );
                   else
                            throw new IllegalArgumentException( x.toString( ) );  
                  return t;
        }
  </code></pre>
  
  <p>And here's my node class </p>
  
  <pre><code>class BinaryNode&lt;AnyKey, AnyValue&gt; {
        BinaryNode( AnyKey theElement, AnyValue theValue ){
            element = theElement;
            value = theValue;
            left = right = null;
         }
         AnyKey             element; 
         AnyValue    value;
          BinaryNode&lt;AnyKey, AnyValue&gt; left;    
         BinaryNode&lt;AnyKey, AnyValue&gt; right;  
       }
  </code></pre>
  
  <p>I am trying to write this method inside my Binary Search Tree </p>
  
  <pre><code>@Override
  public void PrintMostFrequent(int n) {
  
  }
  </code></pre>
  
  <p>Where it will print out the nth most frequent words based on frequency. I have an idea for how to do this  in psuedo code.
  <BR>1. Create a collection to hold nodes
  <BR>2. Add all the nodes from the tree to this collection
  <BR>3. Sort the collection based on counts
  <BR>4. Iterate sorted collection and print out the nth most frequent.</p>
  
  <p>Is this the best way to solve this problem/write this method? I was afraid that creating a separate collection might be spaciously too expensive and the sorting would be computationally expensive as well.</p>