Program to Implement Preorder Tree Traversal

Below is the implementation of Preorder Tree Traversal:

Java
// Java Program to implement Tree
// Preorder Traversal

// Node Class
class Node {
    int data;
    Node left, right;

    public Node(int item) {
        data = item;
        left = right = null;
    }
}

// Class to create Binary Tree
class BinaryTree {
    Node root;
    
      // Preorder Traversal
    void preorderTraversal(Node node) {
        if (node == null)
            return;

        System.out.print(node.data + " "); 
        preorderTraversal(node.left);      
        preorderTraversal(node.right);     
    }

      // main function
    public static void main(String args[]) {
        BinaryTree tree = new BinaryTree();
        tree.root = new Node(1);
        tree.root.left = new Node(2);
        tree.root.right = new Node(3);
        tree.root.left.left = new Node(4);
        tree.root.left.right = new Node(5);

        System.out.println("Preorder traversal of binary tree is ");
        tree.preorderTraversal(tree.root);
    }
}

Output
Preorder traversal of binary tree is 
1 2 4 5 3 

Complexity of the above Method

Time complexity: O(n)
Space complexity: O(n)

Applications of Preorder Traversal in Binary Tree

  • Binary search trees for the efficient searching, insertion and deletion.
  • Expression trees for the representing the expressions in the computer science.
  • Heap trees for the implementing the priority queues.
  • Decision trees for the classification and regression in the machine learning.


Java Program for the Preorder Tree Traversal in Binary Tree

Preorder traversal is the method used to traverse the tree data structure. In the preorder traversal, the nodes are visited in the order: of root, left subtree, and right subtree. It is called as “preorder” because the root node is visited before its children. This traversal technique is widely used in the various tree-based algorithms and applications.

Representation of Binary Tree

Similar Reads

Implementation of the Preorder Tree Traversal

Preorder traversal can be implemented using either recursion or iteration(using the stack)....

Program to Implement Preorder Tree Traversal

Below is the implementation of Preorder Tree Traversal:...