Skip to content
Home » Exploring Binary Tree Traversals: Pre-Order Technique with Java

Exploring Binary Tree Traversals: Pre-Order Technique with Java

Introduction

Welcome to Art of Coding! In our ongoing series about binary trees, we’ve covered various operations such as inserting elements and finding minimum and maximum values. As we continue exploring this indispensable data structure, today’s focus will be on pre-order traversal. Designed for beginners and those refreshing their skills, this article will guide you through understanding pre-order traversal with simplicity and clarity.

What is Pre-Order Traversal?

Pre-order traversal is a method of processing binary trees where the root node is visited first, followed by the left subtree, and finally the right subtree. This approach is termed “pre-order” because the root node is the preeminent focus, processed before its child nodes.

Why is this method useful? Pre-order traversal is particularly valuable for creating a copy of the tree, outputting the tree structure into a readable format, or preparing an expression tree for evaluation. It reflects a straightforward, natural way of exploring the nodes, starting from the top and delving deeper into the branches, which makes it an excellent starting point for understanding tree traversal techniques.

Visualizing Pre-Order Traversal

Now, let’s put a picture to the process with the image below. In pre-order traversal, we start at the root of the tree and work our way down, first visiting the left subtree and then the right. The numbers in red indicate the order in which the nodes are visited.

Binary tree with nodes visited in pre-order traversal sequence: 10, 5, 3, 6, 15, 12, 18.
The order of node visits in Pre-Order Traversal.

In the image, the traversal order is: 10, 5, 3, 6, 15, 12, 18. This sequence is the result of visiting the root node first (10), then moving to the left subtree (visiting 5, then 3, and lastly 6), and finally the right subtree (visiting 15, then 12, and 18 last).

Understanding this pattern is key as it’s the foundation of how pre-order traversal works. It’s a straightforward path: start at the top, and then visit nodes from left to right.

Java Code Example: Pre-Order Traversal

Before we dive into the code, remember that we’ve previously discussed how to add items in a binary search tree. If you’re not familiar with building a binary tree, you might want to check that out first.

Now, let’s see pre-order traversal in action with Java. We have a Node class representing each spot in our binary tree and a preOrder() method that carries out the traversal.

public class Node {
    int value; // Node's value
    Node left; // Left child
    Node right; // Right child

    // Constructor to create a new node with a given value
    public Node(int value) {
        this.value = value;
        this.left = null;
        this.right = null;
    }

    // Method to execute pre-order traversal from the current node
    public void preOrder() {
        System.out.print(value + " "); // Print the current node's value
        if (left != null) {
            left.preOrder(); // Recursively traverse the left subtree
        }
        if (right != null) {
            right.preOrder(); // Recursively traverse the right subtree
        }
    }
    
    // Example of usage
     public static void main(String[] args) {
        Node root = new Node(10);
        root.left = new Node(5);
        root.left.left = new Node(3);
        root.left.right = new Node(6);
        root.right = new Node(15);
        root.right.left = new Node(12);
        root.right.right = new Node(18);

        System.out.println("Pre-order traversal of binary tree is:");
        root.preOrder();
    }
}

This code, when run, will output the pre-order traversal sequence for our binary tree: 10 5 3 6 15 12 18. It initiates from the root and proceeds to each node’s left child before moving to the right, ensuring every node is visited in the pre-determined order.

Complexity Analysis of Pre-Order Traversal

Time Complexity

For pre-order traversal, the time complexity is O(n), where n is the number of nodes in the tree. This is because every node in the binary tree is visited exactly once. No matter how the nodes are arranged, the traversal will always visit all of them, making the time it takes proportional to the number of nodes.

Space Complexity

The space complexity for a recursive pre-order traversal is O(h), where h is the height of the tree. This space is used on the call stack. In the worst-case scenario of a skewed tree (a tree where each parent node has only one child), the height of the tree becomes ‘n’ and thus the space complexity becomes O(n). In a balanced tree, however, the height of the tree is log(n), and the space complexity would thus be O(log(n)) for the call stack during the traversal.

Conclusion

That’s a wrap on pre-order traversal! With the insights and Java code from today’s article, you’re well on your way to understanding binary trees. Try out this traversal method, play with the code, and see what you discover.

Challenge yourself: If you’re feeling confident and want to test your skills further, I encourage you to tackle a related problem on LeetCode. Solving problems in a practical setting will deepen your understanding and sharpen your coding skills. Here’s a link to a relevant LeetCode problem that uses pre-order traversal

Stay tuned: We’ll be exploring in-order and post-order traversals in future posts, so keep an eye on Art of Coding for more tree traversal techniques.

Got questions or want to share your successes with pre-order traversal? Drop a comment below. Let’s grow our coding skills together!

Happy coding!

References

Discover more from Art of Coding

Subscribe now to keep reading and get access to the full archive.

Continue reading