I do not like this implementation as is seems too much complicated. My idea was to implement some BFS algorithm variant.
Some points to notice:
- I use one queue.
- In the begining put the tree root in the queue and dummy
treeNode
delimiter which is recognized by itsdata == -1
.
(I need this for distiguishing between tree levels). - After each level I assign -1 to the queue.
Any suggestions of how to simplify it? (Currently seem to work good)
public void printTreeByLevels() // Should be BFS variant implementation
{
int levelCounter = 0;
boolean currNodeHasChild = false;
Queue<TreeNode> q = new ArrayDeque<TreeNode>();
q.add(m_Root);
q.add(new TreeNode(-1));
System.out.print("Level:" + levelCounter+ " ");
while (!q.isEmpty())
{
TreeNode currentNode = q.poll();
currNodeHasChild = false;
if(currentNode.m_Data == -1)
{
TreeNode nextQueueNode = q.peek();
while(nextQueueNode!= null && currentNode.m_Data == -1)
{
currentNode = q.poll(); //bypassing delimiters
}
if(currentNode.m_Data != -1)
{
levelCounter++;
System.out.println();
System.out.print("Level:" + levelCounter+" ");
}
else if(nextQueueNode == null)
{
break;
}
}
System.out.print("\t"+currentNode.m_Data);
if(currentNode.m_LeftNode!= null)
{
q.add(currentNode.m_LeftNode);
currNodeHasChild = true;
}
if(currentNode.m_RightNode!=null)
{
q.add(currentNode.m_RightNode);
currNodeHasChild = true;
}
if(currNodeHasChild)
{
q.add(new TreeNode(-1)); // sign of next level
}
}
}