Tree’s are one of the many fundamental data structures in Computer Science. Today we’ll be talking about a specific kind of tree called the binary search tree. But before I get into that, let me go over what a Binary Tree is first.
A Binary Tree is a data structure composed of nodes that have at most 2 children. A node is a point on the tree that generally has a value associated with it, though it does not have to. As an example, we’ll look at a binary tree composed of integer nodes.
In the above picture we have a binary tree with seven different nodes. The root node (top of the tree) is the node with the value of 7. The left child of 7 is 8 and the right child of 7 is 9. This relationship follows throughout the whole tree. So now that you’ve seen a binary tree lets look at what makes a binary search tree different.
A binary search tree is a special form of binary tree where starting from the root node, you can travel down the tree and the nodes you travel across must follow the following rules. The left child of any node must be less than or equal to the parent node. The right child of any node must be greater than their parent node. In this case, when we build the tree, it will look different depending on the order we insert the nodes. So lets build the previous tree inserting the nodes in the order of 7, 6, 2, 8, 12, 9, 10. We get…
Any x you see is a child node with a null value. The reason binary search trees are useful is that you can search for any node you want and be guaranteed to find it in O(logn) time, assuming that the tree we build ends up being mostly balanced. There are ways to guarantee that the tree is built in a balanced way but I won’t get into that right now. As a bonus I will provide some sample code that implements a binary search tree in java below.
public class BST {
private Node root;
public BST() {
this.root = null;
}
public Node getRoot() {
return this.root;
}
public void add(int value) {
if(root == null)
root = new Node(value);
else
insert(value, root);
}
private void insert(int value, Node n) {
if(value <= n.getValue()) {
if(n.getLeft() == null)
n.setLeft(new Node(value));
else
insert(value, n.getLeft());
} else {
if(n.getRight() == null)
n.setRight(new Node(value));
else
insert(value, n.getRight());
}
}
public boolean find(int value) {
Node n = this.root;
while(n != null) {
if(value < n.getValue())
n = n.getLeft();
else if(value == n.getValue())
return true;
else
n = n.getRight();
}
return false;
}
}
public class Node {
private int value;
private Node left;
private Node right;
public Node(int value) {
this.value = value;
this.left = null;
this.right = null;
}
public Node getLeft() {
return this.left;
}
public Node getRight() {
return this.right;
}
public int getValue() {
return this.value;
}
public void setLeft(Node left) {
this.left = left;
}
public void setRight(Node right) {
this.right = right;
}
}

