Skip to content

Instantly share code, notes, and snippets.

@zonski
Last active December 31, 2015 11:19
Show Gist options
  • Save zonski/7978767 to your computer and use it in GitHub Desktop.
Save zonski/7978767 to your computer and use it in GitHub Desktop.
public class BinaryTree {
private Node root;
public void insert(int value) {
if (root == null) {
root = new Node(value);
} else {
root.insert(value);
}
}
}
public class Node {
private int value;
private Node left;
private Node right;
public void insert(int value) {
if (value == this.value) {
// we have a duplicate value, no need to store it again (since this tree is only
// used for searching we only need to index each value once)
return;
}
if (value > this.value) {
if (right != null) {
right.insert(value);
} else {
right = new Node(value);
}
} else {
if (left != null) {
left.insert(value);
} else {
left = new Node(value);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment