Quick binary tree question.
I'm implementing a RNL traversal across this binary search tree
here's my pseudocode and the loop I'm trying to implement it with:
1. If there is a node to the right, push current node onto stack, follow right node (by setting it to currentNode).
2. If there is no right node, print current node.
3. If there is a left node push it onto stack. follow left node.
4. If there is no left node pop your current node from the stack.
Code :
Stack nodes = new Stack();
Node currentNode = root;
do {
Node right = currentNode.rightChild;
if (right != null) {
nodes.push(right);
currentNode = right;
}//end if
currentNode.displayNode();
Node left = currentNode.leftChild;
if (left != null) {
nodes.push(left);
currentNode = left;
}//end if
else
nodes.pop();
//end else
} while (! nodes.isEmpty()); //end do while
The output is only 3 nodes out of many, so there is something wrong with it, though I can not figure out what. Many thanks to any who can take a quick look.
Re: Quick binary tree question.
You must traverse all the way left before you can begin pushing onto the stack. This is best done recursively.
Note: I'm taking advantage of passing by reference here. You'll need to initialize a a stack to push the nodes onto before calling this method.
Code :
public void traverse(Node node, Stack toPushOnto)
{
if (node.leftChild != null)
{
traverse(node.leftChild,toPushOnto);
}
toPushOnto.push(node);
if (node.rightChild != null)
{
traverse(node.rightChild,toPushOnto);
}
}