Traverse Pre Order

mail@pastecode.io avatar
unknown
java
a year ago
958 B
0
Indexable
Never
package LAB4;

import java.util.*;

public class traversePreOrder {
    // Declare an ArrayList to store the traversal results
    private ArrayList<Integer> results;

    // Constructor for the traversePreOrder class
    traversePreOrder(Node currentNode, ArrayList<Integer> results)
    {
        // Set the results instance variable to the passed-in ArrayList
        this.results = results;

        // Add the current node's value to the results ArrayList before traversing its subtrees
        results.add(currentNode.value);

        // If the current node has a left child, recursively traverse the left subtree
        if (currentNode.left != null)
        {
            new traversePreOrder(currentNode.left, results);
        }

        // If the current node has a right child, recursively traverse the right subtree
        if (currentNode.right != null)
        {
            new traversePreOrder(currentNode.right, results);
        }
    }
}