Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Red Black tree or AVL tree implementation in Java

Is there any Red Black Tree /AVL Tree data structure implementation in Java collections/Guava/Apache Commons library ? If yes , can you point them to me . Basically I am looking for a data structure where the queries should happen in O(lg n) time . There will also be some updates to the data structure but not quite as often as the queries.

like image 558
Geek Avatar asked Aug 25 '12 12:08

Geek


People also ask

Which is easier to implement AVL tree or red black tree?

Red Black Trees provide faster insertion and removal operations than AVL trees as fewer rotations are done due to relatively relaxed balancing. AVL trees provide complex insertion and removal operations as more rotations are done due to relatively strict balancing.

How do you implement a red black tree in Java?

Red-Black Tree Java Implementation To implement the red-black tree, besides the child nodes left and right , we need a reference to the parent node and the node's color. We store the color in a boolean , defining red as false and black as true . We implement the red-black tree in the RedBlackTree class.

Which is better AVL tree or red black tree?

Red Black tree does not provide efficient searching as Red Black Trees are roughly balanced. AVL trees provide efficient searching as it is strictly balanced tree. Insertion and Deletion are easier in Red Black tree as it requires fewer rotations to balance the tree.

Does Java Use red black tree?

Also, you will find working examples of various operations performed on a red-black tree in C, C++, Java and Python. Red-Black tree is a self-balancing binary search tree in which each node contains an extra bit for denoting the color of the node, either red or black.


1 Answers

Basically I am looking for a data structure where the queries should happen in O(lg n) time

Use a TreeMap. It is backed by a Red-Black tree so it's access time is O(logN) (my emphasis on quote bellow)

public class TreeMap
extends AbstractMap implements
NavigableMap, Cloneable, Serializable

A Red-Black tree based NavigableMap implementation. The map is sorted according to the natural ordering of its keys, or by a Comparator provided at map creation time, depending on which constructor is used.

This implementation provides guaranteed log(n) time cost for the containsKey, get, put and remove operations.

like image 188
Cratylus Avatar answered Oct 26 '22 09:10

Cratylus