Write a Java Program to Perform the preorder tree traversal

Java Program to Perform the preorder tree traversal

Welcome to the World of Online Learning:

Hello Friends “This blog helps you to learn Java programming concepts. You can learn Java  language at your own speed and time. One can learn concepts of Java language by practicing various programs given on various pages of this blog. Enjoy the power of Self-learning using the Internet.”

Java Program to Perform the preorder tree traversal
Java Program to Perform the preorder tree traversal

Write a Java Program to Perform the preorder tree traversal

PROGRAM: Java Program to Perform the preorder tree traversal

/*Java Program to Perform the preorder tree traversal*/

class Node {
int item;
Node left, right;

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

class Tree {
// root of Tree
Node root;

Tree() {
root = null;
}

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

// traverse the root node
System.out.print(node.item + “->”);
// traverse the left child
preorder(node.left);
// traverse the right child
preorder(node.right);
}

public static void main(String[] args) {
// create object of tree
Tree tree = new Tree();

// create nodes of the tree
tree.root = new Node(1);
tree.root.left = new Node(12);
tree.root.right = new Node(9);
tree.root.left.left = new Node(5);
tree.root.left.right = new Node(6);

// preorder tree traversal
System.out.println(“\nPreorder traversal “);
tree.preorder(tree.root);
}
}

Leave a Reply

Your email address will not be published. Required fields are marked *