Create a binary tree java program that allows the user to input 7 elements. The program then outputs the following traversals:
1. Inorder
2. Preorder
3. Post-order
1. Inorder
2. Preorder
3. Post-order
import java.util.Scanner;
class Node {
int data;
Node left, right;
public Node(int item) {
data = item;
left = right = null;
}
}
class BinaryTree {
Node root;
BinaryTree() {
root = null;
}
void insert(int data) {
root = insertRec(root, data);
}
Node insertRec(Node root, int data) {
if (root == null) {
root = new Node(data);
return root;
}
if (data < root.data)
root.left = insertRec(root.left, data);
else if (data > root.data)
root.right = insertRec(root.right, data);
return root;
}
void inorder() {
inorderRec(root);
}
void inorderRec(Node root) {
if (root != null) {
inorderRec(root.left);
System.out.print(root.data + " ");
inorderRec(root.right);
}
}
void preorder() {
preorderRec(root);
}
void preorderRec(Node root) {
if (root != null) {
System.out.print(root.data + " ");
preorderRec(root.left);
preorderRec(root.right);
}
}
void postorder() {
postorderRec(root);
}
void postorderRec(Node root) {
if (root != null) {
postorderRec(root.left);
postorderRec(root.right);
System.out.print(root.data + " ");
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
BinaryTree tree = new BinaryTree();
System.out.println("Enter 7 elements:");
for (int i = 0; i < 7; i++) {
int element = scanner.nextInt();
tree.insert(element);
}
System.out.print("Inorder traversal: ");
tree.inorder();
System.out.println();
System.out.print("Preorder traversal: ");
tree.preorder();
System.out.println();
System.out.print("Postorder traversal: ");
tree.postorder();
System.out.println();
}
}
Node
class represents a node in the binary tree, with data
for storing the value and left
and right
for storing references to the left and right child nodes.BinaryTree
class has methods for inserting nodes into the tree (insert
), performing inorder traversal (inorder
), preorder traversal (preorder
), and postorder traversal (postorder
).main
method, the user is prompted to enter 7 elements, and each element is inserted into the binary tree using the insert
method. Finally, the inorder, preorder, and postorder traversals are printed using the respective methods.