From 00253e78ee21a7772b053fd6d748a513fc61f0da Mon Sep 17 00:00:00 2001 From: Abhinav Sarkar Date: Sat, 29 Jun 2019 16:46:23 +0530 Subject: [PATCH] Adds BST with insert --- .../algorist/BinarySearchTree.java | 93 ++++++++++++++++++- 1 file changed, 92 insertions(+), 1 deletion(-) diff --git a/src/main/java/net/abhinavsarkar/algorist/BinarySearchTree.java b/src/main/java/net/abhinavsarkar/algorist/BinarySearchTree.java index 6103621..98b0a49 100644 --- a/src/main/java/net/abhinavsarkar/algorist/BinarySearchTree.java +++ b/src/main/java/net/abhinavsarkar/algorist/BinarySearchTree.java @@ -1,5 +1,96 @@ package net.abhinavsarkar.algorist; -public class BinarySearchTree +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); + } + }