AVL Trees are a data structure with O(n) space, and O(log n) insert, and O(log n) delete. They store data in a Binary Tree structure with the left branches having a lower value than the right branches. AVL Trees are a type of Binary Tree that is balanced to have the height of the left branch be the height of the right branch give or take 1 of any node.
AVL Trees are balanced to make searching more efficient.
Installation
Download the .lua file, insert it into your game as a Module Script, then use require(PATH TO MODULE) to require the module in one of your scripts.
Example Usage
local AVL = require(script.Parent.AVL_Tree)
-- Initializes the AVL Tree with the values 12, 5, 18, 4, 11, 17, 20
-- 12 also has the extra data "kiwis"
local Tree = AVL.new({4, 11, {12, "kiwis"}, 20, 18, 17, 5, 8})
-- Inserts a node with the value 6 and extra data "watermelons"
Tree:Insert(6, "austrailian jalapenos")
Tree:Insert(7) -- Inserts a node with the value 7 and no extra data
-- Gets the first Node with the value 6 and outputs the data
local Node = Tree:Get(Root, 6)
print(Node.Value, Node.Extra) -- Prints "6 austrailian jalapenos"
-- Removes the first Node with the value 4, in this case, the "austrailian jalapenos" node
Tree:Remove(Root, 7)
-- Attempts to get the node with the value 7, but outputs nil because it has been removed
local Node = Tree:Get(Root, 7)
print(Node) -- Prints nil
What did you mean by repetitive? How should I change that?
And what did you mean by initializing with an array of variable dimensions? I don’t think it’s possible to pre-allocate space for an AVL because of the structure and because Lua doesn’t allow using pointers