Binary Search Tree
Published in
2 min readOct 14, 2015
Binary Search Tree Implementation
public class Node {
private int key;
private Node left;
private Node right;
private Node parent;public Node(int key){this.key = key;}public void setLeft(Node left){this.left = left;}
public void setRight(Node right){this.right = right;}
public void setParent(Node parent){this.parent = parent;}public Node getLeft(){return left;}
public Node getRight(){return right;}
public Node getParent(){return parent;}
public int getKey(){return key;}@Override
public String toString() {
return "Node{" +
"key=" + key +
", left=" + left +
", right=" + right +
", parent=" + parent +
'}';
}
}public class BST {private Node root;/**
* Public method exposed for insert
*
* @param key
*/
public void insert(int key) {
if (root == null) {
root = new Node(key);
return;
} else {
insert(key, root);
}
}/**
* Insert into a Binary Search Tree
*
* @param key value of the node
* @param node
*/
private void insert(int key, Node node) {
if (key <= node.getKey()) {
if (node.getLeft() == null) {
node.setLeft(new Node(key));
return;
}
insert(key, node.getLeft());
} else {
if (key > node.getKey()) {
if (node.getRight() == null) {
node.setRight(new Node(key));
return;
}
insert(key, node.getRight());
}
}
}/**
* Public method exposed for search in a BST
*
* @param key
* @return
*/
public Node search(int key) {
return search(key, root);
}/**
* Return the searched node from a BST
*
* @param key value of the node
* @param node
* @return
*/
private Node search(int key, Node node) {
if (node == null) {
return null;
}
if (node.getKey() == key) {
return node;
}
if (key < node.getKey()) {
return search(key, node.getLeft());
}
return search(key, node.getRight());
}public class Main {public static void main(String[] args) {
BST bst = new BST();int[] numbers = {85,75,190,40,80,140,200,30,130,150,195,135,145,160};
for (int i: numbers){
bst.insert(i);
}
System.out.println((bst.search(85)));
}
}