Learn the fundamentals of binary trees, their properties, and basic operations in Java. Master the essential concepts that form the foundation of tree data structures.
public class TreeNode> {
private T value;
private TreeNode left;
private TreeNode right;
public TreeNode(T value) {
this.value = value;
this.left = null;
this.right = null;
}
// Getters and setters
public T getValue() { return value; }
public TreeNode getLeft() { return left; }
public TreeNode getRight() { return right; }
public void setLeft(TreeNode left) { this.left = left; }
public void setRight(TreeNode right) { this.right = right; }
}
public class BinarySearchTree> {
private TreeNode root;
public BinarySearchTree() {
this.root = null;
}
public void insert(T value) {
if (root == null) {
root = new TreeNode<>(value);
return;
}
insertHelper(root, value);
}
private TreeNode insertHelper(TreeNode current, T value) {
if (current == null) {
return new TreeNode<>(value);
}
int compareResult = value.compareTo(current.getValue());
if (compareResult < 0) {
current.setLeft(insertHelper(current.getLeft(), value));
} else if (compareResult > 0) {
current.setRight(insertHelper(current.getRight(), value));
}
return current;
}
public boolean search(T value) {
return searchHelper(root, value);
}
private boolean searchHelper(TreeNode current, T value) {
if (current == null) {
return false;
}
int compareResult = value.compareTo(current.getValue());
if (compareResult == 0) {
return true;
} else if (compareResult < 0) {
return searchHelper(current.getLeft(), value);
} else {
return searchHelper(current.getRight(), value);
}
}
}
For additional hands-on practice and exercises on binary trees, check out our comprehensive guided project:
Implement these basic BST operations:
Implement all three tree traversal methods:
Try these more challenging exercises:
Online Resources: