I need to implement a preorder traversal method. Traversing a binary tree of nodes.
Im trying to figure out a solution for the problem below. I know how to implement such a method, but the problem is that I can't deviate from the rules my teacher gave me. Which makes this exercise substantial harder.
these are the rules:
- the teacher prohibited the use of recursion
- I have to use a stack
- Begin at the root Node
see the comments in my code for the other restrictions.
public class Node { int key; String name; Node leftChild; Node rightChild; public Node(int key, String name){ this.key = key; this.name = name; } // prints information about a certain node public void visitStap(){ System.out.println("Node name : " + this.name ); System.out.println("Node value : " + this.key + "\n"); } } public void preOrderTraverseTreeNonRecursive(){ Node current = this.root; // Begin at the root Node Stack<Node> theStack = new Stack<Node>(); // extra code is allowed here while(!theStack.empty() || current != null){ // extra code is allowed here if(current != null){ // only 3 lines of code allowed }else{ // only 2 lines of code allowed } } }
I hope someone could help me with this problem.
I came up with a solution after all.