Example – keep the tree balanced

As mentioned in the introduction to the topic of AVL trees, there is a very simple test that can cause a BST tree to become unbalanced. You can just add ordered numbers to create a long and skinny tree. So, let's try to create an example of adding exactly the same set of data to an AVL tree, implemented using the Adjunct library.

The code placed in the Main method in the Program class is as follows:

AvlTree<int> tree = new AvlTree<int>(); for (int i = 1; i < 10; i++) { tree.Add(i); } Console.WriteLine("In-order: " + string.Join(", ", tree.GetInorderEnumerator())); Console.WriteLine("Post-order: " + string.Join(", ", tree.GetPostorderEnumerator())); Console.WriteLine("Breadth-first: " + string.Join(", ", tree.GetBreadthFirstEnumerator())); ...

Get C# Data Structures and Algorithms now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.