Posts

....
Technical Blog for .NET Developers ©

Sunday, May 24, 2020

F# Experimental: BinaryTree

In this example we write the implementation of a very simple demo of use of FSharpX.Collections.Experimental.BinaryTree<T>

Binary Trees organize in the form of Root and Node(s) in the next way:



Install the Nuget for this demo:



We represent the hierarchy of a Demo class:


        class Demo
        {
            public int Id { get; set; }

            public int? HierarchyId { get; set; }

            public string Text { get; set; }
        }  
        
        // with the next function to get the collection
        
        static IEnumerable<Demo> GetDemoItems(int number)
        {
            for (int i = 0; i <= number; i++)
            {
                yield return new Demo
                {
                    Id = i,
                    Text = $"item{i}",
                    HierarchyId = (i == 0) ? default(int?) : (i < 3) ? 0 : (i < 5) ? 1 : (i < 7) ? 2 : 3
                };
            }
        }        
  


And now we simply build the binary tree structure and iterate over the branches with the print function


        static List<Demo> items;

        static void TestBinaryTree()
        {
            items = GetDemoItems(8).ToList();

            BuildBinaryTree(items);
        }

        static void BuildBinaryTree(List<Demo> items)
        {            
            BinaryTree<Demo> btree = GetBranched(items[0]);
            
            Print(btree);
        }

        static BinaryTree<Demo> GetBranched(Demo item)
        {
            if (item == null)
                return BinaryTree<Demo>.Leaf;

            Demo item1 = items.FirstOrDefault(i => i.HierarchyId == item.Id);

            Demo item2 = items.LastOrDefault(i => i.HierarchyId == item.Id);

            return BinaryTree<Demo>.NewBranch(item, GetBranched(item1), GetBranched(item2));
        }

        static void Print(BinaryTree<Demo> btree)
        {
            if (btree == null)
                return;

            if (btree.IsBranch)
            {
                BinaryTree<Demo>.Branch branch = btree as BinaryTree<Demo>.Branch;

                Console.WriteLine($"Id:{branch.Item1.Id} Text:{branch.Item1.Text}");

                Console.WriteLine("Items:");

                Print(branch.Item2);

                Print(branch.Item3);
            }
            else if (btree.IsLeaf)
            {
                Console.WriteLine("Leaf Tree");
            }
        }  
  
The result is this cmd:


<METHOD SOFTWARE 2020 ©>