Certainly! Below is a simple implementation of a binary tree in Java. In this example, each node in the tree has an integer value, and the tree supports basic operations such as insertion and traversal (in-order traversal).
class Node {
int key;
Node left, right;
public Node(int item) {
key = item;
left = right = null;
}
}
public class BinaryTree {
Node root;
public BinaryTree() {
root = null;
}
// Method to insert a key into the binary tree
public void insert(int key) {
root = insertRec(root, key);
}
private Node insertRec(Node root, int key) {
if (root == null) {
root = new Node(key);
return root;
}
if (key < root.key) {
root.left = insertRec(root.left, key);
} else if (key > root.key) {
root.right = insertRec(root.right, key);
}
return root;
}
// Method to perform in-order traversal of the binary tree
public void inOrderTraversal() {
inOrderTraversal(root);
}
private void inOrderTraversal(Node root) {
if (root != null) {
inOrderTraversal(root.left);
System.out.print(root.key + " ");
inOrderTraversal(root.right);
}
}
public static void main(String[] args) {
BinaryTree tree = new BinaryTree();
// Inserting elements into the binary tree
tree.insert(50);
tree.insert(30);
tree.insert(20);
tree.insert(40);
tree.insert(70);
tree.insert(60);
tree.insert(80);
// Performing in-order traversal
System.out.println("In-order traversal:");
tree.inOrderTraversal();
}
}
In this implementation, a Node class represents each node in the binary tree. The BinaryTree class contains the root of the tree and methods for inserting elements and performing in-order traversal. The insertRec method is a recursive helper function for inserting nodes, and inOrderTraversal is a recursive method for in-order traversal.
You can customize and extend this implementation based on your specific requirements, such as adding more operations or modifying the node structure to store additional information.
