I've seen a lot of questions (How to print binary tree diagram?) about how to print out a Tree by level and they all seem to be using nodes, but in the main they define each node and give it specific pointers by hand...I'm looking for a way to do the same thing, print out a tree by level, but you're given a TreeSet of type Integer (e.g. {3,12,28,40,41,58,83}
), and you don't know what's going to be in it until runtime.
For simplicity, output would look something like this:
40
12 58
3 28 41 83
With or without the use of Nodes is fine, but I'd be interested to see a version without them.
EDIT:
To clarify, I'm talking about java.util.TreeSet
.
So I've been working on this since I posted it, and I came up with a method I call getRoot
which takes a TreeSet<Integer>
as a parameter and returns an Integer
which is the middle of the Tree. So for instance if you called it on the example tree, it would return 40
.
So now I'm thinking there's probably a way to recursively do what I'm talking about, by calling getRoot
on sub trees, e.g. tailSet
and headSet
of a tree, if that makes any sense. I'm having trouble making it follow through every branch of the tree, however. My code so far:
public TreeSet<Integer> recursivePlease(TreeSet<Integer> t){
if (t.size()<=1){ //base case
System.out.println(t.first());
return t;
}else{
System.out.println(getRoot(t));
return recursivePlease((TreeSet<Integer>) t.headSet(getRoot(t)));
}
}
and this...works. But it just prints the left side of the tree. Any help on making this method print the whole tree, or other ideas entirely, are greatly appreciated.