Skip to content

Instantly share code, notes, and snippets.

@apremalal
Last active December 13, 2015 21:08
Show Gist options
  • Save apremalal/4975299 to your computer and use it in GitHub Desktop.
Save apremalal/4975299 to your computer and use it in GitHub Desktop.
This is an implementation of the binary search tree. Reference - Introduction to Algorithms
public class BinarySearchTree {
void in_order_tree_walk(Node x) {
in_order_tree_walk(x.left);
System.out.println(x.key);
in_order_tree_walk(x.right);
}
void insert(Node T, Node x) {
Node y = T;
while (y != null) {
if (y.key < x.key) {
if (y.right == null)
y.right = x;
else
y = y.right;
} else {
if (y.left == null)
y.left = x;
else
y = y.left;
}
}
}
Node minimum(Node x) {
while (x.left != null) {
x = x.left;
}
return x;
}
Node maximum(Node x) {
while (x.right != null) {
x = x.right;
}
return x;
}
Node treeSearch(Node x, int key) {
if (x == null || x.key == key) {
return x;
}
if (x.key < key) {
return treeSearch(x.left, key);
} else {
return treeSearch(x.right, key);
}
}
Node itereativeTreeSearch(Node x, int key) {
while (x != null && x.key != key) {
if (x.key < key)
x = x.right;
else
x = x.left;
}
return x;
}
}
class Node {
Node left;
Node right;
int key;
Node(int key) {
this.key = key;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment