Search code examples
javaarraystreebinary-treeheapsort

Create an array with the keys of nodes


I currently have a binary tree setup and would like to create an array with the keys so I can do a heap sort operation on them. How would I go about doing that?

Here is what I currently have:

public static void main(String args[]) throws IOException
{
    BufferedReader in = new BufferedReader(new FileReader("employee.txt"));
    String line;
    Heap employee = new Heap();

    while((line = in.readLine())!= null)
    {
        String[]text = line.split(" ");
        employee.insert(Double.parseDouble(text[0]), Double.parseDouble(text[1]));

    }
    in.close();
}

The binary tree that I am using is pretty standard but I can post it if needed. The "text[0]" segment is what the key is for each node.


Solution

  • One possibility is to use the TreeSet class in combination with a Comparator. The TreeSet can behave like a heap. The class is well documented, but if you have more questions, ask.

    EDIT

    Take a look here. The accepted answer shows you an implementation of a binary tree. What you need now is a sorting function implementation in that class, which may be triggered at element insertion or manually when needed.

    I still don't see how you want to switch a tree into a heap as they are different things. I guess you mean the tree should be "read" say from left to right and so rearranged?