Skip to content

Instantly share code, notes, and snippets.

@orzklv
Created March 28, 2025 18:10
Show Gist options
  • Save orzklv/2dc738e31bd73731aac0afbb994151f1 to your computer and use it in GitHub Desktop.
Save orzklv/2dc738e31bd73731aac0afbb994151f1 to your computer and use it in GitHub Desktop.
Java devs, get the rope!
-- Algebraic data type definition
data Tree a = Empty | Node (Tree a) a (Tree a) deriving (Show)
-- Insertion function
insert :: (Ord a) => a -> Tree a -> Tree a
insert x Empty = Node Empty x Empty
insert x (Node left v right)
| x < v = Node (insert x left) v right
| otherwise = Node left v (insert x right)
-- Search function
search :: (Ord a) => a -> Tree a -> Bool
search _ Empty = False
search x (Node left v right)
| x == v = True
| x < v = search x left
| otherwise = search x right
--- #############################################
let tree = foldr insert Empty [5,3,7,9,1]
search 7 tree -- True
// Java class-based binary tree implementation
class TreeNode<T extends Comparable<T>> {
T value;
TreeNode<T> left;
TreeNode<T> right;
TreeNode(T value) {
this.value = value;
this.left = null;
this.right = null;
}
void insert(T newValue) {
if (newValue.compareTo(value) < 0) {
if (left == null) left = new TreeNode<>(newValue);
else left.insert(newValue);
} else {
if (right == null) right = new TreeNode<>(newValue);
else right.insert(newValue);
}
}
boolean search(T target) {
if (value.equals(target)) return true;
else if (target.compareTo(value) < 0) return left != null && left.search(target);
else return right != null && right.search(target);
}
}
// #################################################
TreeNode<Integer> root = new TreeNode<>(5);
root.insert(3);
root.insert(7);
boolean found = root.search(7); // true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment