A Binary Tree is a type of tree data structure in which each node has at most two children, commonly referred to as the “left child” and the “right child.”
Java Implementation
Below is a Java implementation of a simple binary tree with basic functionalities such as adding nodes and traversing the tree.
class Node {
int data;
Node left;
Node right;
public Node(int data) {
this.data = data;
this.left = null;
this.right = null;
}
}
public class BinaryTree {
Node root;
public BinaryTree() {
root = null;
}
// Add a node
public Node addRecursive(Node current, int data) {
if (current == null) {
return new Node(data);
}
if (data < current.data) {
current.left = addRecursive(current.left, data);
} else if (data > current.data) {
current.right = addRecursive(current.right, data);
}
return current;
}
public void add(int data) {
root = addRecursive(root, data);
}
// In-order traversal
public void inOrderTraversal(Node node) {
if (node != null) {
inOrderTraversal(node.left);
System.out.print(node.data + " ");
inOrderTraversal(node.right);
}
}
public static void main(String[] args) {
BinaryTree tree = new BinaryTree();
tree.add(6);
tree.add(4);
tree.add(8);
tree.add(3);
tree.add(5);
tree.add(7);
tree.add(9);
System.out.println("In-order traversal:");
tree.inOrderTraversal(tree.root); // Output: 3 4 5 6 7 8 9
}
}
Binary Trees are foundational structures that have a wide range of applications. In the next post, we will look into Binary Search Trees which are specialized Binary Trees used in practical applications.