package net.abhinavsarkar.algorist; public class BinarySearchTree,V> { private Node 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,V> { private K key; private V val; private Node left; private Node 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 bst = new BinarySearchTree<>(); bst.insert("b", "barista"); bst.insert("a", "abhinav"); bst.insert("c", "carpool"); bst.insert("d", "carl"); System.out.println(bst); } }