Implementing a nonrecursive preorder traversal method

240 Views Asked by At

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.

1

There are 1 best solutions below

0
On BEST ANSWER

I came up with a solution after all.

public void preOrderTraverseTreeNonRecursive(){
    Node current = this.root; // Begin bij de root
    Stack<Node> theStack = new Stack<Node>();

    while(!theStack.empty() || current != null){
        if(current != null){
            // only 3 lines of code allowed
            current.visitStap(); // print current Node information
            theStack.push(current); // push current Node on to the stack
            current = current.leftChild; //  set current node to leftChild
        }else{
            // only 2 lines of code allowed
            current = theStack.pop().rightChild; // pop Node from stack and
                                                 // get its rightChild 

        }
    }
}