-2

I am working on a problem where I need to find the pair in which the difference of value is at most k. Now tree set in java does that for me but I am curious to know how this is working. I am assuming it creates some sort of bucket and map that bucket with some values in a hashmap.

I checked the definition in intelliJ but couldn't find anything which explains how it works.

I found this code in Treemap and now i want to understand how it is actually working

final Entry<K,V> getCeilingEntry(K key) {
        Entry<K,V> p = root;
        while (p != null) {
            int cmp = compare(key, p.key);
            if (cmp < 0) {
                if (p.left != null)
                    p = p.left;
                else
                    return p;
            } else if (cmp > 0) {
                if (p.right != null) {
                    p = p.right;
                } else {
                    Entry<K,V> parent = p.parent;
                    Entry<K,V> ch = p;
                    while (parent != null && ch == parent.right) {
                        ch = parent;
                        parent = parent.parent;
                    }
                    return parent;
                }
            } else
                return p;
        }
        return null;
    }
Atul Agrawal
  • 1,474
  • 5
  • 22
  • 41
  • 1
    Nope. It uses a [tree](https://en.wikipedia.org/wiki/Tree_(data_structure)). Clue's in the name... (note that this means most operations are `O(n lg n)` rather than `O(1)` as with a hash table) – Boris the Spider Feb 10 '19 at 18:13
  • You're not going to get an answer to your second question - it's far too broad. Java is open source - what stops you from reading the code? – Boris the Spider Feb 11 '19 at 09:52

1 Answers1

2

The Set data structures in Java are backed by Maps. The set stores elements as keys in the map and uses static object as a placeholder for values. Hence, the ceiling and floor functions are also delegated to the map. For example;

public E ceiling(E e) {
   return m.ceilingKey(e);
}

So the TreeSet is backed by a TreeMap.

The TreeMap is a red-black tree (at least in Java 7 and onwards) which is a self-balancing binary search tree. https://en.wikipedia.org/wiki/Red%E2%80%93black_tree

Hope this helps

Laksitha Ranasingha
  • 4,321
  • 1
  • 28
  • 33