AVL tree implementation

The avl_tree unit implements a general-purpose AVL (balanced) tree class: the class and it's associated data node class .

List classes Exception support and string handling Represents a node in the tree. TAVLTreeNode represents a single node in the AVL tree. It contains references to the other nodes in the tree, and provides a Data pointer which can be used to store the data, associated with the node. Reference to the parent node in the tree. Parent contains a reference to the parent node of the current node. It is Nil for the root node. left Right Reference to the left subtree of the current node. Left contains a reference to the first node in the left subtree of the current node. It is Nil if there is no left subtree. Parent Right Reference to the right subtree of the current node. Right contains a reference to the first node in the right subtree of the current node. It is Nil if there is no right subtree. Parent Left Balance of the current node Balance is the balance of the current node, that is, the Depth of the right subtree minus the depth of the left subtree. If balance is one of -1, 0, 1 then the node is considered balanced. TreeDepth The data item associated with this node. Data is the data item associated with this node. It is not freed when the node is freed, the programmer is responsible for freeing the actual data. Clears the node's data Clear clears all pointers and references in the node. It does not free the memory pointed to by these references. Level of the node in the tree below TreeDepth is the height of the node: this is the largest height of the left or right nodes, plus 1. If no nodes appear below this node (left and Right are Nil), the depth is 1. Balance The depth of the current node Create a new node instance Create a new tree node instance. Free the node Destroy frees the current node. It does not free the left or right or data nodes. Clear AVL tree component

TAVLTree maintains a balanced AVL tree. The tree consists of nodes, each of which has a Data pointer associated with it. The TAVLTree component offers methods to balance and search the tree.

By default, the list is searched with a simple pointer comparison algorithm, but a custom search mechanism can be specified in the OnCompare property.

Root node of the tree Root is the root node of the tree. It should not be set explicitly, only use the Add, Delete, Remove, RemovePointer, or Clear methods to manipulate the items in the tree. Find a data item in the tree.

Find uses the default OnCompare comparing function to find the Data pointer in the tree. It returns the TAVLTreeNode instance that results in a successful compare with the Data pointer, or Nil if none is found.

The default OnCompare function compares the actual pointers, which means that by default Find will give the same result as FindPointer.

OnCompare FindKey
Tree node corresponding to Data item. Data item to search for. Find a data item in the tree using alternate compare mechanism FindKey uses the specified OnCompareKeyWithData comparing function to find the Key pointer in the tree It returns the TAVLTreeNode instance that matches the Data pointer, or Nil if none is found. OnCompare Find Tree node corresponding to Key item. Data item to search for. Data pointer comparison callback Find successor to node

FindSuccessor returns the successor to ANode: this is the leftmost node in the right subtree, or the leftmost node above the node ANode. This can of course be Nil.

This method is used when a node must be inserted at the rightmost position.

The succeding node The node from which to start the search

FindPrecessor returns the successor to ANode: this is the rightmost node in the left subtree, or the rightmost node above the node ANode. This can of course be Nil.

This method is used when a node must be inserted at the leftmost position.

The preceding node The node from which to start the search Find the lowest (leftmost) node in the tree. FindLowest returns the leftmost node in the tree, i.e. the node which is reached when descending from the rootnode via the left subtrees. FindHighest The leftmost (lowest) node in the tree. Find the highest (rightmost) node in the tree. FindHighest returns the rightmost node in the tree, i.e. the node which is reached when descending from the rootnode via the Right subtrees. FindLowest The rightmost (highest) node in the tree. Find the node closest to the data in the tree FindNearest searches the node in the data tree that is closest to the specified Data. If Data appears in the tree, then its node is returned. FindHighest FindLowest Find FindKey The node that is closest to Data The data item to search for. Search for a data pointer

FindPointer searches for a node where the actual data pointer equals Data. This is a more fine search than find, where a custom compare function can be used.

The default OnCompare compares the data pointers, so the default Find will return the same node as FindPointer

The node that matches Data The data pointer to search for. Find the node most left to a specified data node

FindLeftMost finds the node most left from the Data node. It starts at the preceding node for Data and tries to move as far right in the tree as possible.

This operation corresponds to finding the previous item in a list.

The leftmost node relative to Data The data item where to start the search from Find the node most right to a specified node

FindRightMost finds the node most right from the Data node. It starts at the succeding node for Data and tries to move as far left in the tree as possible.

This operation corresponds to finding the next item in a list.

The rightmost node relative to Data The data item where to start the search from Find the node most left to a specified key node FindLeftMostKey finds the node most left from the node associated with Key. It starts at the preceding node for Key and tries to move as far left in the tree as possible. The leftmost node for Key Key identifiying the node where to start the search. Callback to compare key value with data item Find the node most right to a specified key node FindRightMostKey finds the node most left from the node associated with Key. It starts at the succeding node for Key and tries to move as far right in the tree as possible. The rightmost node for Key Key identifiying the node where to start the search. Callback to compare key value with data item Find the node most left to a specified node with the same data FindLefMostSameKey finds the node most left from and with the same data as the specified node ANode. The treenode that was found, or nil if none found The node to start the search from Find the node most right of a specified node with the same data FindRighMostSameKey finds the node most right from and with the same data as the specified node ANode. The treenode that was found, or nil if none found The node to start the search from Add a new node to the tree Add adds a new Data or Node to the tree. It inserts the node so that the tree is maximally balanced by rebalancing the tree after the insert. In case a data pointer is added to the tree, then the node that was created is returned. Node to add to the tree Resulting node in case a data pointer is added. Data item to add to the tree Delete a node from the tree

Delete removes the node from the tree. The node is not freed, but is passed to a instance for future reuse. The data that the node represents is also not freed.

The tree is rebalanced after the node was deleted.

The node to delete from the tree. Remove a data item from the list. Remove finds the node associated with Data using find and, if found, deletes it from the tree. Only the first occurrence of Data will be removed. Data item to remove from the tree. Remove a pointer item from the list. Remove uses FindPointer to find the node associated with the pointer Data and, if found, deletes it from the tree. Only the first occurrence of Data will be removed. Pointer to remove from the tree Move data to the nearest left element

MoveDataLeftMost moves the data from the node ANode to the nearest left location relative to Anode. It returns the new node where the data is positioned. The data from the former left node will be switched to ANode.

This operation corresponds to switching the current with the previous element in a list.

Node whose data most be moved Move data to the nearest right element

MoveDataRightMost moves the data from the node ANode to the rightmost location relative to Anode. It returns the new node where the data is positioned. The data from the former rightmost node will be switched to ANode.

This operation corresponds to switching the current with the next element in a list.

Node whose data most be moved Compare function used when comparing nodes OnCompare is the comparing function used when the data of 2 nodes must be compared. By default, the function simply compares the 2 data pointers. A different function can be specified on creation. Clears the tree

Clear deletes all nodes from the tree. The nodes themselves are not freed, and the data pointer in the nodes is also not freed.

If the node's data must be freed as well, use instead.

Clears the tree and frees nodes FreeAndClear deletes all nodes from the tree. The data pointer in the nodes is assumed to be an object, and is freed prior to deleting the node from the tree. Delete a node from the tree and destroy it FreeAndDelete deletes a node from the tree, and destroys the data pointer: The data pointer in the nodes is assumed to be an object, and is freed by calling its destructor. Node which must be deleted Number of nodes in the tree. Count is the number of nodes in the tree. Check the consistency of the tree

ConsistencyCheck checks the correctness of the tree. It returns 0 if the tree is internally consistent, and a negative number if the tree contais an error somewhere.

-1
The Count property doesn't match the actual node count
-2
A left node does not point to the correct parent
-3
A left node is larger than parent node
-4
A right node does not point to the correct parent
-5
A right node is less than parent node
-6
The balance of a node is not calculated correctly
0 if the tree is OK, a negative number if something is wrong. Write the contents of the tree consistency check to the stream WriteReportToStream writes a visual representation of the tree to the stream S. The total number of written bytes is returnes in StreamSize. This method is only useful for debugging purposes. Stream to write the tree report to Total number of bytes written Return the tree report as a string ReportAsString calls WriteReportToStream and retuns the stream data as a string. The tree report as a string Create a new instance of TAVLTree Create initializes a new instance of . An alternate OnCompare can be provided: the default OnCompare method compares the 2 data pointers of a node. OnCompare Alternative node comparison method Destroy the TAVLTree instance Destroy clears the nodes (the node data is not freed) and then destroys the TAVLTree instance. TAVLTreeNode Node memory manager TAVLTreeNodeMemManager is an internal object used by the avl_tree unit. Normally, no instance of this object should be created: An instance is created by the unit initialization code, and freed when the unit is finalized. Return a node to the free list

DisposeNode is used to put the node ANode in the list of free nodes, or optionally destroy it if the free list is full. After a call to DisposeNode, ANode must be considered invalid.

Node to dispose of Create a new TAVLTreeNode instance NewNode returns a new instance. If there is a node in the free list, itare returned. If no more free nodes are present, a new node is created. The new node. Minimum amount of free nodes to be kept. MinimumFreeNode is the minimum amount of nodes that must be kept in the free nodes list. Maximum amount of free nodes in the list MaximumFreeNodeRatio is the maximum amount of free nodes that should be kept in the list: if a node is disposed of, then the ratio of the free nodes versus the total amount of nodes is checked, and if it is less than the MaximumFreeNodeRatio ratio but larger than the minimum amount of free nodes, then the node is disposed of instead of added to the free list. Number of nodes in the list. Count is the total number of nodes in the list, used or not. Frees all unused nodes Clear removes all unused nodes from the list and frees them. Create a new instance of TAVLTreeNodeMemManager Create initializes a new instance of TAVLTreeNodeMemManager. Destroy calls clear to clean up the free node list and then calls the inherited destroy. Base class for a node memory manager

TBaseAVLTreeNodeManager is an abstract class from which a descendent can be created that manages creating and disposing of tree nodes (instances of ) for a tree instance. No instance of this class should be created, it is a purely abstract class. The default descendant of this class used by an TAVLTree instance is .

The method can be used to set the node manager that a TAVLTree instance should use.

Called when the AVL tree needs a new node NewNode is called by when it needs a new node in . It must be implemented by descendants to return a new instance. Called when the AVL tree no longer needs node DisposeNode is called by when it no longer needs a instance. The manager may decide to re-use the instance for later use instead of destroying it. Set the node instance manager to use

SetNodeManager sets the node manager instance used by the tree to newmgr. It should be called before any nodes are added to the tree. The TAVLTree instance will not destroy the nodemanager, thus the same instance of the tree node manager can be used to manager the nodes of multiple TAVLTree instances.

By default, a single instance of is used to manage the nodes of all TAVLTree instances.

Node to dispose of New node instance Enumerator for the TAVLTree tree nodes TAVLTreeNodeEnumerator is a class which implements the enumerator interface for the . It enumerates all the nodes in the tree. Create a new instance of TAVLTreeNodeEnumerator Create creates a new instance of TAVLTreeNodeEnumerator and saves the Tree argument for later use in the enumerator. TAVLTree instance to enumerate Move to next node in the tree. MoveNext will return the lowest node in the tree to start with, and for all other calls returns the successor node of the current node with . Next node. Current node in the tree Current is the current node in the enumeration. New node manager to use Automatically free the node manager when the tree is destroyed. Get an enumerator for the tree. GetEnumerator returns an instance of the standard tree node enumerator . An instance of an enumerator class.