Skip to content

Instantly share code, notes, and snippets.

@trplll
Created August 23, 2017 21:39
Show Gist options
  • Save trplll/b6c15fa6e239fa950c4003349afd825f to your computer and use it in GitHub Desktop.
Save trplll/b6c15fa6e239fa950c4003349afd825f to your computer and use it in GitHub Desktop.
Basic Binary Tree DS in Java
package ds;
public class BasicBinaryTree<X extends Comparable<X>> {
private Node root;
private int size;
public BasicBinaryTree() {
this.root = null;
}
public int size() {
return size;
}
public void add(X item) {
Node node = new Node(item);
if (root == null) {
this.root = node;
System.out.println("Set root: " + node.getItem());
this.size++;
} else {
insert(this.root, node);
}
}
public boolean contains(X item) {
Node node;
node = this.root;
boolean entries = true;
while (entries) {
if (node.getItem().equals(item)) {
return true;
} else if (item.compareTo(node.getItem()) < 0) {
node = node.getLeft();
if (node.item == null) {
entries = false;
return false;
}
} else if (item.compareTo(node.getItem()) > 0) {
node = node.getRight();
if (node.item == null) {
entries = false;
return false;
}
}
}
return true;
}
private Node getNode(X item) {
Node currentNode = this.root;
while (currentNode != null) {
int val = item.compareTo(currentNode.getItem());
// see if the node is a match
if (val == 0) {
return currentNode;
}
// if the val is less than 0 we go to the left side of the tree
else if (val < 0) {
currentNode = currentNode.getLeft();
}
// otherwise we go to the right side
else {
currentNode = currentNode.getRight();
}
}
return null;
}
public void insert(Node parent, Node child) {
// child less than parent goes on left
if (child.getItem().compareTo(parent.getItem()) < 0) {
// if left node null then x marks spot
if (parent.getLeft() == null) {
parent.setLeft(child);
child.setParent(parent);
this.size++;
} else {
insert(parent.getLeft(), child);
}
}
// child more than parent goes on right
if (child.getItem().compareTo(parent.getItem()) > 0) {
// if right node null then x marks spot
if (parent.getRight() == null) {
parent.setRight(child);
child.setParent(parent);
this.size++;
} else {
insert(parent.getRight(), child);
}
}
}
private class Node {
private Node left;
private Node right;
private Node parent;
private X item;
public Node(X item) {
this.left = null;
this.right = null;
this.parent = null;
this.item = item;
}
public Node getLeft() {
return left;
}
public void setLeft(Node left) {
this.left = left;
}
public Node getRight() {
return right;
}
public void setRight(Node right) {
this.right = right;
}
public Node getParent() {
return parent;
}
public void setParent(Node parent) {
this.parent = parent;
}
public X getItem() {
return item;
}
public void setItem(X item) {
this.item = item;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment