w3resource

Java: Get the preorder traversal of its nodes' values of a given a binary tree.

Java Basic: Exercise-125 with Solution

Write a Java program to get the preorder traversal of the values of the nodes in a binary tree.
Example:
Expected output: 10 20 40 50 30

Sample Binary Tree

Java Basic Exercises: Sample Binary Tree.

Preorder Traversal:

Java Basic Exercises: Get the preorder traversal of its nodes' values of a given a binary tree.

Sample Solution:

Java Code:

class Node
{
    int key;
    Node left, right;

    public Node(int item)
    {
        // Constructor to create a new Node with the given item
        key = item;
        left = right = null;
    }
}

class BinaryTree
{
    Node root;

    BinaryTree()
    {
        // Constructor to create an empty binary tree
        root = null;
    }

    void print_Preorder(Node node)
    {
        if (node == null)
            return;

        // Print the key of the current node
        System.out.print(node.key + " ");

        // Recursively print the left subtree in preorder
        print_Preorder(node.left);

        // Recursively print the right subtree in preorder
        print_Preorder(node.right);
    }

    void print_Preorder()  
    {   
        // Wrapper method to start printing the tree in preorder
        print_Preorder(root); 
    }

    public static void main(String[] args)
    {
        BinaryTree tree = new BinaryTree();
        
        // Create a binary tree with nodes and keys
        tree.root = new Node(55);
        tree.root.left = new Node(21);
        tree.root.right = new Node(80);
        tree.root.left.left = new Node(9);
        tree.root.left.right = new Node(29);
        tree.root.right.left = new Node(76);
        tree.root.right.right = new Node(91);

        // Display a message and initiate the preorder traversal
        System.out.println("Preorder traversal of binary tree is: ");
        tree.print_Preorder();
    }
}

Sample Output:

Preorder traversal of binary tree is: 
55 21 9 29 80 76 91  

Flowchart:

Flowchart: Java exercises: Get the preorder traversal of its nodes' values of a given a binary tree.

Java Code Editor:

Previous: Write a Java program to find the index of a value in a sorted array. If the value does not find return the index where it would be if it were inserted in order.
Next: Write a Java program to get the inorder traversal of its nodes' values of a given a binary tree.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/java-exercises/basic/java-basic-exercise-125.php