That's already known problem: to return an array of linked lists that contain values of elements at each level. Eg for tree with depth n there should be n linked lists.
I wrote the solution:
public ArrayList<LinkedList<Integer>> levelLists() {
class NodeLevel {
public BinaryTreeNode node;
public int level;
public NodeLevel(BinaryTreeNode n, int l) {
this.node = n;
this.level = l;
}
}
ArrayList<LinkedList<Integer>> levels = new ArrayList<LinkedList<Integer>>();
Queue<NodeLevel> queue = new LinkedList<NodeLevel>();
int currentLevel = -1;
queue.add(new NodeLevel(root, 0));
while (!queue.isEmpty()) {
NodeLevel current = queue.poll();
if (current.level != currentLevel) {
levels.add(new LinkedList<Integer>());
currentLevel++;
}
levels.get(levels.size() - 1).add(current.node.value);
if (current.node.getLeftChild() != null) {
queue.add(new NodeLevel(current.node.getLeftChild(), currentLevel + 1));
}
if (current.node.getRightChild() != null) {
queue
.add(new NodeLevel(current.node.getRightChild(), currentLevel + 1));
}
}
return levels;
}
But I am sure it's very space inefficient. I am quite sure it can be done without remembering level for each node (and so without this whole additional class NodeLevel). I was thinking about just adding null node to the queue at the end of each level, but still I don't know how to indicate end of the level without this whole structure. Can anyone give me a hint?