Reputation: 2670
I am having problems with the level order traversal of my binary tree whilst using recursion. I am inputing the following values: 50,60,70,30,20,10 Here is the code I am using:
public void levelOrder(Node localRoot){
if(localRoot != null){
if(localRoot.leftChild != null && localRoot.rightChild != null){
System.out.print(localRoot.iData + " ");
System.out.print(localRoot.leftChild.iData + " ");
System.out.print(localRoot.rightChild.iData + " ");
levelOrder(localRoot.leftChild);
levelOrder(localRoot.rightChild);
}
else if(localRoot.rightChild == null && localRoot.leftChild == null){
;
}
else if(localRoot.rightChild == null){
System.out.print(localRoot.leftChild.iData + " ");
//levelOrder(localRoot.leftChild);
}
else{
System.out.print(localRoot.rightChild.iData + " ");
//levelOrder(localRoot.rightChild);
}
}
}
Is recursion possible without using a stack? Because currently this function is taking me all the way to the left and then it goes right. What could I be doing differently?
My output for this code is: 50, 30, 60, 20, 70 and it does not print 10.
Upvotes: 2
Views: 10703
Reputation: 11
public void level() {
printLevel(root);
}
public void printLevel(Node current)
{
if(current != null){
if(current.leftChild != null && current.rightChild != null){
System.out.print(current.iData + " ");
System.out.print(current.leftChild.iData + " ");
System.out.print(current.rightChild.iData + " ");
printLevel(current.leftChild);
printLevel(current.rightChild);
}
else if(current.rightChild == null && current.leftChild == null){
;
}
else if(current.rightChild == null){
System.out.print(current.leftChild.iData + " ");
//levelOrder(current.leftChild);
}
else{
System.out.print(current.rightChild.iData + " ");
//levelOrder(current.rightChild);
}
}
}
Upvotes: 1
Reputation: 1120
You can do the trick with a Queue:
private Queue<Key> getLevelOrderKeys(Node root){
if (root == null) {
return null;
}
Queue<Key> keyQueue = new ArrayDeque<Key>(); //return value. Queue with the level order keys
Queue<Node> nodeQueue = new ArrayDeque<Node>();
nodeQueue.add(root);
//while there is at least one discovered node
while(!nodeQueue.isEmpty()) {
Node current = nodeQueue.poll();
keyQueue.add(current.key);
if (current.left != null){
nodeQueue.add(current.left);
}
if (current.right != null){
nodeQueue.add(current.right);
}
}
return keyQueue;
}
Upvotes: 0
Reputation: 512
Interestingly this is a fairly common question (google "recursive bread first traversal" and there are several links to stackoverflow of similar answers )
by far the best one is here
Performing Breadth First Search recursively
and i agree with the author of the top answer, there is really no point in turning an iterative algorithm (breadth first traversal) into a recursive solution. As mentioned yes its easy to turn iteration into tail recursion, but to what end? and you would still need a queue.
Upvotes: 1