Adds BST with insert
parent
cf8d64192d
commit
00253e78ee
|
@ -1,5 +1,96 @@
|
||||||
package net.abhinavsarkar.algorist;
|
package net.abhinavsarkar.algorist;
|
||||||
|
|
||||||
public class BinarySearchTree
|
public class BinarySearchTree<K extends Comparable<K>,V>
|
||||||
{
|
{
|
||||||
|
|
||||||
|
private Node<K,V> root;
|
||||||
|
|
||||||
|
public BinarySearchTree() {
|
||||||
|
this.root = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void insert(K key, V val) {
|
||||||
|
if (this.root == null) {
|
||||||
|
this.root = new Node<>(key, val);
|
||||||
|
} else {
|
||||||
|
this.root.insert(key, val);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public String toString() {
|
||||||
|
return this.root.toString(0).toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static class Node<K extends Comparable<K>,V> {
|
||||||
|
private K key;
|
||||||
|
private V val;
|
||||||
|
private Node<K,V> left;
|
||||||
|
private Node<K,V> right;
|
||||||
|
|
||||||
|
public Node(K key, V val) {
|
||||||
|
this.key = key;
|
||||||
|
this.val = val;
|
||||||
|
}
|
||||||
|
public V getVal()
|
||||||
|
{
|
||||||
|
return val;
|
||||||
|
}
|
||||||
|
public K getKey()
|
||||||
|
{
|
||||||
|
return key;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void insert(K key, V val)
|
||||||
|
{
|
||||||
|
if (this.key == key) {
|
||||||
|
this.val = val;
|
||||||
|
} else if (this.key.compareTo(key) > 0) {
|
||||||
|
if (this.left == null) {
|
||||||
|
this.left = new Node<>(key, val);
|
||||||
|
} else {
|
||||||
|
this.left.insert(key, val);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if (this.right == null) {
|
||||||
|
this.right = new Node<>(key, val);
|
||||||
|
} else {
|
||||||
|
this.right.insert(key, val);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public StringBuilder toString(int level) {
|
||||||
|
StringBuilder sb = new StringBuilder()
|
||||||
|
.append(gutter(level))
|
||||||
|
.append("<" + key + ":" + val + ">\n");
|
||||||
|
if (this.left != null) {
|
||||||
|
sb.append(this.left.toString(level + 1));
|
||||||
|
}
|
||||||
|
if (this.right != null) {
|
||||||
|
sb.append(this.right.toString(level + 1));
|
||||||
|
}
|
||||||
|
return sb;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static StringBuilder gutter(int times) {
|
||||||
|
StringBuilder sb = new StringBuilder();
|
||||||
|
for (int i = 0; i < times; i++)
|
||||||
|
{
|
||||||
|
sb.append(' ');
|
||||||
|
}
|
||||||
|
return sb.append("|— ");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void main(String[] args)
|
||||||
|
{
|
||||||
|
BinarySearchTree<String, String> bst = new BinarySearchTree<>();
|
||||||
|
bst.insert("b", "barista");
|
||||||
|
bst.insert("a", "abhinav");
|
||||||
|
bst.insert("c", "carpool");
|
||||||
|
bst.insert("d", "carl");
|
||||||
|
|
||||||
|
System.out.println(bst);
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in New Issue