|
| 1 | +package ds; |
| 2 | + |
| 3 | +/** |
| 4 | + * Created by sherxon on 12/16/16. |
| 5 | + */ |
| 6 | +// Binary Search Tree, two nodes (left, right) one parent. |
| 7 | +// insert -> O(h) can be O(n) if input is sorted |
| 8 | +// search -> O(h) can be O(n) if input is sorted |
| 9 | +// remove -> O(h) can be O(n) if input is sorted |
| 10 | +// no duplicate is allowed, for duplicate supported BST look BSTWithDuplicate.java |
| 11 | +// most methods are recursive, look BSTIterative.java for iterative approach BST |
| 12 | + |
| 13 | +public class BST<K extends Comparable> { |
| 14 | + private Node root; |
| 15 | + |
| 16 | + public void insert(K k) { |
| 17 | + root = putRecursive(root, k, null); |
| 18 | + } |
| 19 | + |
| 20 | + public boolean search(K k) { |
| 21 | + return findRecursive(k, root); |
| 22 | + } |
| 23 | + public void delete(K k){ |
| 24 | + |
| 25 | + } |
| 26 | + public K findMax(){ |
| 27 | + return findMaxRecursive(root); |
| 28 | + } |
| 29 | + public K findMin(){ |
| 30 | + return findMinRecursive(root); |
| 31 | + } |
| 32 | + |
| 33 | + private K findMaxRecursive(Node x) { |
| 34 | + if(x.right==null)return x.value; |
| 35 | + else return findMaxRecursive(x.right); |
| 36 | + } |
| 37 | + private K findMinRecursive(Node x) { |
| 38 | + if(x.left==null)return x.value; |
| 39 | + else return findMinRecursive(x.left); |
| 40 | + } |
| 41 | + |
| 42 | + private boolean findRecursive(K k, Node x) { |
| 43 | + if (x == null) return false; |
| 44 | + if (x.value.equals(k)) |
| 45 | + return true; |
| 46 | + else if (x.value.compareTo(k) > 0) |
| 47 | + return findRecursive(k, x.left); |
| 48 | + else |
| 49 | + return findRecursive(k, x.right); |
| 50 | + } |
| 51 | + |
| 52 | + private Node putRecursive(Node x, K k, Node parent) { |
| 53 | + if (x == null) return new Node(k, parent); |
| 54 | + if (x.value.compareTo(k) > 0) |
| 55 | + x.left = putRecursive(x.left, k, x); |
| 56 | + else if (x.value.compareTo(k) < 0) |
| 57 | + x.right = putRecursive(x.right, k, x); |
| 58 | + x.size = 1 + size(x.left) + size(x.right); |
| 59 | + return x; |
| 60 | + } |
| 61 | + |
| 62 | + |
| 63 | + |
| 64 | + //rank of tree |
| 65 | + private int size(Node x) { |
| 66 | + return x == null ? 0 : x.size; |
| 67 | + } |
| 68 | + |
| 69 | + // BST node |
| 70 | + private class Node { |
| 71 | + K value; |
| 72 | + int size = 1; |
| 73 | + Node left; |
| 74 | + Node right; |
| 75 | + Node parent; |
| 76 | + |
| 77 | + |
| 78 | + public Node(K k, Node parent) { |
| 79 | + this.value = k; |
| 80 | + this.parent = parent; |
| 81 | + } |
| 82 | + } |
| 83 | +} |
0 commit comments