Exemplo n.º 1
0
        //public static void Main(string[] args)
        //{
        //DoubleLinkedList<int> list = new DoubleLinkedList<int>();
        //SingleLinkedList<int> list = new SingleLinkedList<int>();
        //int index = 5;
        //Console.WriteLine("The ADD Method and toString");
        //Add Method and toString
        //list.Add(12);
        //list.Add(20);
        //list.Add(1);
        //list.Add(0);
        //list.Add(121);
        //list.Add(420);
        //list.Add(78);
        //list.Add(90);
        //list.Add(34);
        //list.Add(4);
        //Console.WriteLine(list.ToString());
        //Console.WriteLine("\nThe COUNT Method");
        //Console.WriteLine("The the count of this list is: " + list.Count);
        //Console.WriteLine("\nThe INSERT Method");
        //Console.WriteLine("I am inserting the number 22 at index: " + index);
        //list.Insert(22, index);
        //Console.WriteLine("New List: " + list.ToString());
        //Console.WriteLine("\nThe COUNT Method");
        //Console.WriteLine("The the count of this list is: " + list.Count);
        //Console.WriteLine("\nThe Get Method");
        //Console.WriteLine("What is at index " + index + ": " + list.Get(index));
        //Console.WriteLine("\nThe REMOVEAT Method");
        //Console.WriteLine("What is at index " + (list.Count - 1) + ": " + list.Get((list.Count - 1)));
        //Console.WriteLine("I am removing the element at index " + (list.Count - 1) + ": " + list.RemoveAt((list.Count - 1)));
        //Console.WriteLine("New List: " + list.ToString());
        //Console.WriteLine("\nThe COUNT Method");
        //Console.WriteLine("The the count of this list is: " + list.Count);
        //Console.WriteLine("\nThe INSERT Method");
        //Console.WriteLine("I am inserting the number 15 at index: " + );
        //list.Insert(15,(list.Count - 1));
        //Console.WriteLine("New List: " + list.ToString());
        //Console.WriteLine("\nThe COUNT Method");
        //Console.WriteLine("The the count of this list is: " + list.Count);
        //Console.WriteLine("\nThe SEARCH Method");
        //Console.WriteLine("Searching for 1: " + list.Search(1));
        //Console.WriteLine("\nThe REMOVE Method");
        //Console.WriteLine(list.Remove());
        //Console.WriteLine("New List: " + list.ToString());
        //Console.WriteLine("\nThe COUNT Method");
        //Console.WriteLine("The the count of this list is: " + list.Count);
        //Console.WriteLine("\nThe REMOVELAST Method");
        //Console.WriteLine(list.RemoveLast());
        //Console.WriteLine("New List: " + list.ToString());
        //Console.WriteLine("\nThe COUNT Method");
        //Console.WriteLine("The the count of this list is: " + list.Count);
        //Console.WriteLine("\nThe CLEAR Method");
        //list.Clear();
        //Console.WriteLine("New List: " + list.ToString());
        //    Console.WriteLine("\nThe REMOVEAT Method");
        //    Console.WriteLine("What is at index " + index + ": " + list.Get(index));
        //    //Console.WriteLine("I am removing the element at index " + index + ": " + list.RemoveAt(index));
        //    Console.WriteLine("New List: " + list.ToString());
        //    Console.WriteLine("\nThe COUNT Method");
        //    Console.WriteLine("The the count of this list is: " + list.Count);
        //}
        public static void Main(string[] args)
        {
            BinarySearchTree<int> bst = new BinarySearchTree<int>();

            bst.Add(24);
            bst.Add(10);
            bst.Add(1337);

            //bst.Add(50);
            //bst.Add(1472);
            //bst.Add(72);
            //bst.Add(1360);
            //bst.Add(1345);
            //bst.Add(54);

            //bst.Add(20);
            //bst.Add(9);
            //bst.Add(19);
            //bst.Add(14);
            //bst.Add(67);

            //bst.Add(35);
            //bst.Add(80);
            //bst.Add(65);
            //bst.Add(24);
            //bst.Add(5);

            Console.WriteLine("Count:" + bst.Count);
            //Console.WriteLine("\ncontains 24: " + bst.Contains(24));

            //Console.WriteLine("\ncontains 0: " + bst.Contains(0));

            //Console.WriteLine("\nInorder:" + bst.Inorder());

            //Console.WriteLine("\nRemove: I'm removing 17 : " + bst.Remove(17));
            Console.WriteLine("\nInorder:" + bst.Inorder());

            Console.WriteLine("\nRemove: I'm removing 24 : " + bst.Remove(24));

            //bst.Clear();

            Console.WriteLine("\nCount:" + bst.Count);

            Console.WriteLine("\nInorder:" + bst.Inorder());
            //Console.WriteLine("\nPostorder:" + bst.Postorder());
            //Console.WriteLine("\nPreorder:" + bst.Preorder());

            //Console.WriteLine();
            //Console.WriteLine("\nPreorder:" + bst.Preorder());

            //Console.WriteLine();
            //Console.WriteLine("\nPostorder:" + bst.Postorder());

            foreach (var item in bst.ToArray())
            {
                Console.WriteLine(item);
            }

            Console.ReadLine();
        }
Exemplo n.º 2
0
 public static void UnitTest()
 {
     Console.WriteLine ("----- Testing BinarySearchTree<int> -----");
     Console.Write ("Creating new BinarySearchTree of type <int>...");
     BinarySearchTree<int> test = new BinarySearchTree<int> (); d ();
     Console.Write ("Adding value 50...");
     test.Add (50); d ();
     Console.Write ("Adding value 25...");
     test.Add (25); d ();
     Console.Write ("Adding value 75...");
     test.Add (75); d ();
     Console.Write ("Checking for correct structure (25/50\\75)...");
     Debug.Assert (test.root.value == 50);
     Debug.Assert (test.root.nodes[0].value == 25);
     Debug.Assert (test.root.nodes[1].value == 75);
     d ();
     Console.Write ("Checking if BinarySearchTree.Contains(75) works...");
     Debug.Assert (test.Contains(75)); d ();
     Console.Write ("Testing BinarySearchTree.TraversePre()...");
     Debug.Assert( test.TraversePre ((x) => Console.Write (x.value + " ")) == "50 25 75 "); d ();
     Console.Write ("Testing BinarySearchTree.TraverseInOrder()...");
     Debug.Assert( test.TraverseInOrder ((x) => Console.Write (x.value + " ")) == "25 50 75 "); d ();
     Console.Write ("Testing BinarySearchTree.TraversePost()...");
     Debug.Assert( test.TraversePost ((x) => Console.Write (x.value + " ")) == "25 75 50 "); d ();
     Console.WriteLine ("----- Testing BinarySearchTree<string> -----");
     Console.Write ("Creating new BinarySearchTree of type <string> with custom IComparer...");
     BinarySearchTree<string> foo = new BinarySearchTree<string> ( new StringComparer() ); d ();
     Console.Write ("Adding value Urist McSmashes...");
     foo.Add ("Urist McSmashes"); d ();
     Console.Write ("Adding value Gordon Freeman...");
     foo.Add ("Gordon Freeman"); d ();
     Console.Write ("Adding value Winston Smith...");
     foo.Add ("Winston Smith"); d ();
     Console.Write ("Checking for correct structure (Gordon Freeman/Urist McSmashes\\Winston Smith)...");
     Debug.Assert (foo.root.value == "Urist McSmashes");
     Debug.Assert (foo.root.nodes[0].value == "Gordon Freeman");
     Debug.Assert (foo.root.nodes[1].value == "Winston Smith");
     d ();
     Console.WriteLine ("----- Testing BinaryExpressionTree -----");
     Console.Write ("Creating new BinaryExpressionTree with expression \"5 + 2 * 8 - 6 / 4\"...");
     BinaryExpressionTree bar = new BinaryExpressionTree ("5 + 2 * 8 - 6 / 4"); d ();
     Console.Write ("Checking for correct structure...");
     Debug.Assert( bar.TraverseInOrder ((x) => Console.Write (x.value + " ")) == "4 47 6 45 8 42 2 43 5 ");
     Debug.Assert( bar.root.value == 45 ); // -
     Debug.Assert( bar.root.nodes[0].value == 47 ); // /
     Debug.Assert( bar.root.nodes[0].nodes[0].value == 4 );
     Debug.Assert( bar.root.nodes[0].nodes[1].value == 6 );
     Debug.Assert( bar.root.nodes[1].value == 43 ); // +
     Debug.Assert( bar.root.nodes[1].nodes[1].value == 5 );
     Debug.Assert( bar.root.nodes[1].nodes[0].value == 42 ); // *
     Debug.Assert( bar.root.nodes[1].nodes[0].nodes[0].value == 8 );
     Debug.Assert( bar.root.nodes[1].nodes[0].nodes[1].value == 2 );
     d ();
     Console.Write ("Checking for correct answer \"5 + 2 * 8 - 6 / 4\" = " + (5.0 + 2.0 * 8.0 - 6.0 / 4.0) + "...");
     Debug.Assert (bar.Eval () == (5.0 + 2.0 * 8.0 - 6.0 / 4.0)); d ();
     Console.WriteLine ("Everything appears to be in order! Although asserts in C# don't actually end execution so there's no real way for me to know!");
 }
 public void BinarySearchTreePositiveTest()
 {
     var bst = new BinarySearchTree<int, string>();
     bst.Add(10, "Mr. and Mrs. Iqbal Ahmed Mughal");
     bst.Add(1, "Sana");
     bst.Add(2, "Mehwish");
     bst.Add(3, "Adil");
     bst.Add(4, "Ammara");
     Assert.AreEqual("Ammara", bst.Retrieve(4));
 }
        public void TestBinarySearchTreeEquals2()
        {
            BinarySearchTree<int> tree1 = new BinarySearchTree<int>(1, 9, 7);

            BinarySearchTree<int> tree2 = new BinarySearchTree<int>();
            tree2.Add(7);
            tree2.Add(5);
            tree2.Add(9);

            Assert.AreEqual(false, tree1.Equals(tree2));
        }
Exemplo n.º 5
0
        public void Simple()
        {
            var tree = new BinarySearchTree<int, string>();

            Assert.IsFalse(tree.ContainsKey(5));

            tree.Add(4, "4");
            Assert.AreEqual(tree[4], "4");
            Assert.IsTrue(tree.ContainsKey(4));
            Assert.IsFalse(tree.ContainsKey(5));

            tree.Add(6, "6");
            Assert.AreEqual(tree[6], "6");
            Assert.IsTrue(tree.ContainsKey(4));
            Assert.IsFalse(tree.ContainsKey(5));
            Assert.IsTrue(tree.ContainsKey(6));

            tree.Add(2, "2");
            Assert.AreEqual(tree[2], "2");
            Assert.IsTrue(tree.ContainsKey(2));
            Assert.IsTrue(tree.ContainsKey(4));
            Assert.IsFalse(tree.ContainsKey(5));
            Assert.IsTrue(tree.ContainsKey(6));

            tree.Add(5, "5");
            Assert.AreEqual(tree[5], "5");
            Assert.IsTrue(tree.ContainsKey(2));
            Assert.IsTrue(tree.ContainsKey(4));
            Assert.IsTrue(tree.ContainsKey(5));
            Assert.IsTrue(tree.ContainsKey(6));

            var rand = new Random();

            tree = new BinarySearchTree<int, string>();

            var list = new List<int>();

            for (var i = 0; i < 100; i++)
            {
                int r;

                do
                {
                    r = rand.Next(5000);
                }
                while (list.Contains(r));

                list.Add(r);

                tree.Add(r, null);

                Assert.IsTrue(tree.ContainsKey(r));
            }
        }
        public void AddTest()
        {
            var bst = new BinarySearchTree<int>() { 10, 15, 5, 4, 7, 20, 14, 0, -5, -8, -2, -1 };
            bst.Add(55);
            bst.Add(-55);
            bst.Add(35);

            // TODO: Dump as array then compare against expected array
            Assert.IsTrue(bst.Contains(55), "Did not add element correctly");
            Assert.IsTrue(bst.Contains(-55), "Did not add element correctly");
            Assert.IsTrue(bst.Contains(35), "Did not add element correctly");
        }
Exemplo n.º 7
0
        public void KeyValuePair()
        {
            var tree = new BinarySearchTree<int, string>();

            Assert.IsFalse(tree.Contains(new KeyValuePair<int, string>(5, "5")));

            tree.Add(4, "4");
            Assert.IsTrue(tree.Contains(new KeyValuePair<int, string>(4, "4")));
            Assert.IsFalse(tree.Contains(new KeyValuePair<int, string>(4, "5")));

            tree.Add(6, "6");
            Assert.IsTrue(tree.Contains(new KeyValuePair<int, string>(6, "6")));
            Assert.IsFalse(tree.Contains(new KeyValuePair<int, string>(6, "5")));
        }
        static void Main(string[] args)
        {
            BinarySearchTree<int> tree = new BinarySearchTree<int>();
            tree.Add(2);
            tree.Add(4);
            tree.Add(1);
            tree.Add(20);
            tree.Add(15);

            foreach (var v in tree.GetEnumeratorPreorder())
            {
                Console.WriteLine(v);
            }
            Console.ReadLine();
        }
Exemplo n.º 9
0
        public void BinaryTreeMustSortTheSameAsSortedDictionary()
        {
            // Arrange
            var asm = Assembly.GetExecutingAssembly();
            var importer = new Importer(asm.GetManifestResourceStream("ClientImport.Tests.records.txt"), ',');
            var dictionary = new SortedDictionary<string, IPerson>();
            var tree = new BinarySearchTree<string, IPerson>();

            //Act
            importer.Data
                           .ToList()
                           .ForEach(record =>
                           {
                               var person = new Person
                               {
                                   FirstName = record.FirstName,
                                   Surname = record.Surname,
                                   Age = Convert.ToInt16(record.Age)
                               };
                               var key = PersonRepository.BuildKey(person, SortKey.SurnameFirstNameAge);
                               if (tree.Find(key) == null)
                                   tree.Add(key, person);
                           }
                              );

            tree
                .ToList()
                .Shuffle() //Shuffle result from binary tree, to test sorting
                .ForEach(r => dictionary.Add(PersonRepository.BuildKey(r.KeyValue.Value, SortKey.SurnameFirstNameAge), r.KeyValue.Value));

            var expected = dictionary.Select(r => r.Value).ToList();
            var actual = tree.Select(n => n.KeyValue.Value).ToList();
            // Assert
            CollectionAssert.AreEqual(expected, actual);
        }
Exemplo n.º 10
0
        public void Simple()
        {
            var tree = new BinarySearchTree<int, string>();

            var dictionary = new Dictionary<int, string>();

            var rand = new Random(Convert.ToInt32(DateTime.Now.Ticks % Int32.MaxValue));

            for (var i = 0; i < 50; i++)
            {
                var gen = rand.Next(2000);

                while (dictionary.ContainsKey(gen))
                {
                    gen = rand.Next(2000);
                }

                dictionary.Add(gen, null);

                tree.Add(gen, gen.ToString());

                string val;

                Assert.AreEqual(tree.Count, i + 1);

                tree.TryGetValue(gen, out val);
                Assert.AreEqual(val, gen.ToString());
                Assert.AreEqual(tree[gen], gen.ToString());
            }

            string val2;
            tree.TryGetValue(2001, out val2);
            Assert.IsNull(val2);
        }
Exemplo n.º 11
0
        public void KeyValuePair()
        {
            var tree = new BinarySearchTree<int, string>();

            var dictionary = new Dictionary<int, string>();

            var rand = new Random(Convert.ToInt32(DateTime.Now.Ticks % Int32.MaxValue));

            for (var i = 0; i < 50; i++)
            {
                var gen = rand.Next(2000);

                while (dictionary.ContainsKey(gen))
                {
                    gen = rand.Next(2000);
                }

                dictionary.Add(gen, null);

                tree.Add(new KeyValuePair<int, string>(gen, gen.ToString()));

                Assert.AreEqual(tree.Count, i + 1);
                Assert.IsTrue(tree.ContainsKey(gen));
            }
        }
Exemplo n.º 12
0
        static void Main()
        {
            var sb = new StringBuilder();

            var tree = new BinarySearchTree<int>(15);

            for (int i = 0; i < 30; i++)
            {
                tree.Add(i);
            }

            var clonedNode = (TreeNode<int>)tree.Root.Clone();

            sb.AppendLine(tree.ToString())
                .AppendLine("Tree root: " + tree.Root.ToString())
                .AppendLine("Tree contains 7? " + tree.Contains(7).ToString())
                .AppendLine("Cloned root: " + clonedNode.ToString())
                .AppendLine("Cloned Equals root? " + (clonedNode.Equals(tree.Root)).ToString())
                .AppendLine("Cloned == root? " + (clonedNode == tree.Root).ToString())
                .AppendLine("Cloned != root? " + (clonedNode != tree.Root).ToString())
                .AppendLine("12 deleted. New tree:");

            Console.Write(sb.ToString());

            tree.Delete(12);
            Console.WriteLine(tree.ToString());
        }
Exemplo n.º 13
0
        public void Simple()
        {
            var tree = new BinarySearchTree<int, string>();

            var dictionary = new Dictionary<int, string>();

            var rand = new Random(Convert.ToInt32(DateTime.Now.Ticks % Int32.MaxValue));

            for (var i = 0; i < 50; i++)
            {
                var gen = rand.Next(2000);

                while (dictionary.ContainsKey(gen))
                {
                    gen = rand.Next(2000);
                }

                dictionary.Add(gen, null);

                tree.Add(gen, gen.ToString());

                Assert.AreEqual(tree.Count, i + 1);
                Assert.IsTrue(tree.ContainsKey(gen));
            }

            using (var enumerator = dictionary.GetEnumerator())
            {
                while (enumerator.MoveNext())
                {
                    Assert.IsTrue(tree.Remove(enumerator.Current));
                }
            }
        }
Exemplo n.º 14
0
        static void Main()
        {
            BinarySearchTree<int> intTree = new BinarySearchTree<int>();

            intTree.Add(3);
            intTree.Add(1);
            intTree.Add(6);

            Console.WriteLine("Call intTree.ToString();");
            Console.WriteLine(intTree);

            Console.WriteLine("\nUse foreach:");

            foreach (var item in intTree)
            {
                Console.WriteLine(item);
            }

            BinarySearchTree<int> compareTree = intTree;

            Console.WriteLine("\nIs intTree equals with compareTree: {0}", compareTree.Equals(intTree));

            compareTree = new BinarySearchTree<int>();
            compareTree.Add(7);

            Console.WriteLine("\nIs intTree != with compareTree: {0}", compareTree != intTree);
            Console.WriteLine("\nIs intTree equals with compareTree: {0}", compareTree.Equals(intTree));

            Console.WriteLine("\nTest Clone");

            compareTree = intTree.Clone();

            Console.WriteLine("intTree: {0}", intTree);
            Console.WriteLine("compareTree: {0}", compareTree);

            int searchedNumber = -3;

            Console.WriteLine("\nintTree contains {0} = {1}", searchedNumber, intTree.Contains(searchedNumber));

            int deleteNumber = 3;
            intTree.Add(3);

            Console.WriteLine("\nintTree before deleting: {0}", intTree);
            Console.WriteLine("\nintTree Delete {0}, deleted elements are: {1}", deleteNumber, intTree.Delete(deleteNumber));
            Console.WriteLine("\nintTree after deleting: {0}", intTree);
        }
Exemplo n.º 15
0
        public void TestIsEmpty()
        {
            var tree = new BinarySearchTree<string>();
            Assert.IsTrue(tree.IsEmpty);

            tree.Add("a");

            Assert.IsFalse(tree.IsEmpty);
        }
        public void ShouldAddTreeNodeAsRootWhenTreeIsCreatedWithoutRootNode()
        {
            var node = new BinaryTreeNode<int>(null, 15);

            var binaryTree = new BinarySearchTree<int>();

            binaryTree.Add(node);

            Assert.AreEqual(node, binaryTree.Root);
        }
Exemplo n.º 17
0
    static void Main()
    {
        BinarySearchTree<int> tree = new BinarySearchTree<int>();

        for (int i = 1; i < 10; i+=2)
            tree.Add(i);

        Console.WriteLine(tree);

        Console.WriteLine((tree.Clone() as BinarySearchTree<int>) == tree);
    }
Exemplo n.º 18
0
        public void TestTreeCount()
        {
            var tree = new BinarySearchTree<int>();
            var size = 100;

            Node<int> node = null;
            for (int i = 0; i < size; i++)
            {
                node = tree.Add(i);
            }

            Assert.AreEqual(tree.Count, size);

            tree.Remove(node);

            Assert.AreEqual(tree.Count, size - 1);

            tree.Add(101);

            Assert.AreEqual(tree.Count, size);
        }
Exemplo n.º 19
0
        public void Set()
        {
            var tree = new BinarySearchTree<int, string>();

            for (var i = 20; i > 10; i--)
            {
                tree.Add(i, i.ToString());
            }

            for (var i = 0; i < 10; i++)
            {
                tree.Add(i, i.ToString());
            }

            Assert.AreEqual(tree[0], "0");
            tree[0] = "1";
            Assert.AreEqual(tree[0], "1");

            tree[1] = "4";
            Assert.AreEqual(tree[1], "4");
        }
Exemplo n.º 20
0
    static void Main(string[] args)
    {
        BinarySearchTree<int> tree = new BinarySearchTree<int>();

        tree.Add(4);
        tree.Add(3);
        tree.Add(1);
        tree.Add(100);
        tree.Add(5);

        BinarySearchTree<int> newTree = (BinarySearchTree<int>)tree.Clone();

        tree.Delete(4);

        Console.WriteLine(tree);
        Console.WriteLine(newTree);

        Console.WriteLine(tree.Search(100));

        Console.WriteLine(tree.Equals(newTree));
    }
        public void ShouldAddAfterTheRootNodeAsRightNode()
        {
            var root = new BinaryTreeNode<int>(null, 15);

            var binaryTree = new BinarySearchTree<int>(root);

            var nodeToAdd = new BinaryTreeNode<int>(null, 17);
            binaryTree.Add(nodeToAdd);

            Assert.AreEqual(nodeToAdd, root.RightChild, "Should be added as right node!");
            Assert.AreEqual(root, nodeToAdd.Parent, "Parent node should be the root node, after adding!");
        }
        public void BinaryTreeTest_Add_Count_Int()
        {
            BinarySearchTree <int> a = new BinarySearchTree <int>();

            a.Add(1);
            a.Add(4);
            a.Add(0);
            a.Add(15);
            a.Add(65);
            a.Add(11);
            a.Add(76);
            a.Add(8);
            a.Add(64);
            Assert.AreEqual(9, a.Count);
            CollectionAssert.AreEqual(new int[] { 0, 1, 4, 8, 11, 15, 64, 65, 76 }, a.InOrder());
            CollectionAssert.AreEqual(new int[] { 0, 8, 11, 64, 76, 65, 15, 4, 1 }, a.PostOrder());
            CollectionAssert.AreEqual(new int[] { 1, 0, 4, 15, 11, 8, 65, 64, 76 }, a.PreOrder());
        }
        public bool Contains_IntegerTreeWithComparer_IsNodeInTheTree(int nodeToSearch, int[] nodes)
        {
            var comparer = Comparer <int> .Create((x, y) => x.ToString().Length - y.ToString().Length);

            var tree = new BinarySearchTree <int>(comparer, BinarySearchTree <int> .Traversal.PreOrder);

            foreach (var node in nodes)
            {
                tree.Add(node);
            }

            return(tree.Contains(nodeToSearch));
        }
        public void Clear_IntegerTreeWithDefaultComparer_EmptyTree(int[] nodes)
        {
            var tree = new BinarySearchTree <int>(BinarySearchTree <int> .Traversal.PreOrder);

            foreach (var node in nodes)
            {
                tree.Add(node);
            }

            tree.Clear();

            Assert.IsTrue(tree.Count == 0);
        }
        public void InOrderTraversalLoadTest()
        {
            var data = GetRandomArray();

            var tree = new BinarySearchTree <int, bool>();

            tree.Add(data.Select(x => new BinarySearchTree <int, bool> .Node(x, false)));

            var actual   = tree.InOrderTraversalNonRecursive().Select(x => x.Key).ToArray();
            var expected = data.OrderBy(x => x).ToArray();

            CollectionAssert.AreEquivalent(expected, actual);
        }
        public void BinaryTree_Create_CustomStringComparer_Postoder_Test()
        {
            string[] result = { "rtyeuyyu", "aaaaa", "dfge", "rt", "adcd", };

            BinarySearchTree <string> binarySearchTree = new BinarySearchTree <string>(new ComparerStringLength());

            binarySearchTree.Add("adcd");
            binarySearchTree.Add("dfge");
            binarySearchTree.Add("aaaaa");
            binarySearchTree.Add("rt");
            binarySearchTree.Add("rtyeuyyu");

            string[] array = new string[5];
            var      i     = 0;

            foreach (var node in binarySearchTree.Postoder)
            {
                array[i++] = node;
            }

            CollectionAssert.AreEqual(array, result);
        }
Exemplo n.º 27
0
        public void Add(IPerson person)
        {
            var key = BuildKey(person, defaultSortKey);

            if (data.Find(key) == null)
            {
                data.Add(key, person);
            }
            else
            {
                throw new ArgumentException("Duplicate Key found.");
            }
        }
Exemplo n.º 28
0
        public void Enumerator_Point_SortedArray()
        {
            var point1 = new Point()
            {
                X = 8, Y = 9
            };

            var point2 = new Point()
            {
                X = 4, Y = 3
            };

            var point3 = new Point()
            {
                X = 7, Y = 6
            };

            var comparer = new CustomPointComparer();

            var tree = new BinarySearchTree <Point>(comparer.Compare);

            tree.Add(point1);
            tree.Add(point2);
            tree.Add(point3);


            var resArray = new Point[3];

            int i = 0;

            foreach (var item in tree)
            {
                resArray[i++] = item;
            }

            Point[] expArr = { point2, point3, point1 };

            Assert.AreEqual(expArr, resArray);
        }
Exemplo n.º 29
0
    static void Main()
    {
        BinarySearchTree<int> tree1 = new BinarySearchTree<int>();
        tree1.Add(11);
        tree1.Add(35);
        tree1.Add(7);
        tree1.Add(16);
        tree1.Add(23);
        tree1.Add(13);
        tree1.Add(17);

        //tree1.Remove(11);
        //tree1.Remove(7);
        //tree1.Remove(16);
        //tree1.Remove(23);
        //tree1.Remove(13);

        //Console.WriteLine(tree1);
        //Console.WriteLine(tree1.AsString(false));

        BinarySearchTree<int> tree2 = new BinarySearchTree<int>();
        tree2.Add(11);
        tree2.Add(35);
        tree2.Add(7);
        tree2.Add(16);
        tree2.Add(23);
        tree2.Add(13);
        tree2.Add(17);

        Console.WriteLine(tree2);

        BinarySearchTree<int> tree3 = tree2.Clone();

        Console.WriteLine(tree3);
        Console.WriteLine(tree3 == tree2);

        tree2.Remove(23);
        tree2.Add(2323);

        Console.WriteLine(tree2);
        Console.WriteLine(tree3);

        foreach (int item in tree2)
        {
            Console.WriteLine(item);
        }

        //Console.WriteLine(tree2.GetHashCode());
    }
        public void Can_Enumerate_VT_PostOrder_With_Default_Comparer(int[] data, int[] expected)
        {
            BinarySearchTree <Point> tree = new BinarySearchTree <Point>(CompareByX);

            foreach (var item in data)
            {
                tree.Add(new Point(item, 10));
            }

            List <Point> books = expected.Select(item => new Point(item, 10)).ToList();

            CollectionAssert.AreEqual(books, tree.PostOrder().ToArray());
        }
        public void Can_Enumerate_RT_PreOrder_With_Custom_Comparer(int[] data, int[] expected)
        {
            BinarySearchTree <Book> tree = new BinarySearchTree <Book>(CompareByZerosCount);

            foreach (var item in data)
            {
                tree.Add(new Book(item));
            }

            List <Book> books = expected.Select(item => new Book(item)).ToList();

            CollectionAssert.AreEqual(books, tree.PreOrder().ToArray());
        }
Exemplo n.º 32
0
        public void ShouldAddAfterTheRootNodeAsRightNode()
        {
            var root = new BinaryTreeNode <int>(null, 15);

            var binaryTree = new BinarySearchTree <int>(root);

            var nodeToAdd = new BinaryTreeNode <int>(null, 17);

            binaryTree.Add(nodeToAdd);

            Assert.AreEqual(nodeToAdd, root.RightChild, "Should be added as right node!");
            Assert.AreEqual(root, nodeToAdd.Parent, "Parent node should be the root node, after adding!");
        }
        public void AddToTreeAndFindTest()
        {
            var dataArray = new int[] { 8, 10, 3, 6, 1, 4, 7, 14, 13 };
            var tree      = new BinarySearchTree <int, int>();

            foreach (var data in dataArray)
            {
                tree.Add(data, data);
            }

            Assert.AreEqual(dataArray.Length, tree.Count);
            Assert.IsTrue(Array.TrueForAll(dataArray, e => e == tree.Find(e)));
        }
        public void BinaryTreeAlgorithms_Test()
        {
            var tree1 = new BinarySearchTree <int>();

            tree1.Add(24);
            tree1.Add(12);
            tree1.Add(15);
            tree1.Add(67);
            tree1.Add(32);
            tree1.Add(13);
            tree1.Add(89);
            tree1.Add(9);



            tree1.Remove(13);
            tree1.Remove(24);
            //Assert.IsTrue(tree1.PathSum(tree1.Root(), 45));
            //Assert.IsTrue(tree1.PathSum(tree1.Root(), 51));
            //Assert.IsFalse(tree1.PathSum(tree1.Root(), 42));

            //Assert.AreEqual(8, tree1.Size(tree1.Root()));

            //Assert.AreEqual(9, tree1.Minimum(tree1.Root()));

            //Assert.AreEqual(89, tree1.Maximum(tree1.Root()));

            //Assert.IsTrue(BinaryTree.AreTwoTreesEqual(tree1.Root(), tree2.Root()));

            Console.WriteLine("Inorder traversal ");
            tree1.Inorder(tree1.Root);
            Console.WriteLine(" ");

            TreeAlgorithms <int> .Mirror(tree1.Root);

            Console.WriteLine("Inorder traversal of the Mirror tree");
            tree1.Inorder(tree1.Root);
            Console.WriteLine(" ");

            Console.WriteLine();
            Console.WriteLine("Preorder traversal");
            tree1.Preorder(tree1.Root);
            Console.WriteLine(" ");

            Console.WriteLine();
            Console.WriteLine("Postorder traversal");
            tree1.Postorder(tree1.Root);
            Console.WriteLine(" ");
        }
        public void Add_IntegerTreeWithDefaultComparer_TreeWithAddedNodes(int[] nodes, int[] expectedArray)
        {
            var tree = new BinarySearchTree <int>(BinarySearchTree <int> .Traversal.PreOrder);

            foreach (var node in nodes)
            {
                tree.Add(node);
            }

            var resultArray = tree.ToArray();

            CollectionAssert.AreEqual(expectedArray, resultArray);
        }
        public void TreeHeightTest1()
        {
            BinarySearchTree BST = new BinarySearchTree();

            //BST.root = BST.Add(BST.root, 10);
            BST.root = BST.Add(BST.root, 15);
            //BST.root = BST.Add(BST.root, 5);
            //BST.root = BST.Add(BST.root, 8);
            //BST.root = BST.Add(BST.root, 12);
            //BST.root = BST.Add(BST.root, 19);

            Assert.Equal(1, BinaryTreeHeight.Program.CalculateBinaryTreeHeight(BST.root));
        }
Exemplo n.º 37
0
        public void Delete_RootWithOneChildren_NodeSuccessfullyRemoved()
        {
            BinarySearchTree <int> tree = new BinarySearchTree <int>();

            //       6
            //      /
            //     3
            //    /  \
            //   1    5
            //       /
            //      4

            tree.Add(6);
            tree.Add(3);
            tree.Add(1);
            tree.Add(5);
            tree.Add(4);

            tree.Delete(6);

            Assert.That(tree.ToArray(), Is.EqualTo(new[] { 1, 3, 4, 5 }));
        }
Exemplo n.º 38
0
        public void Contains_returns_false_for_value_not_in_tree()
        {
            // Arrange
            BinarySearchTree tree = new BinarySearchTree();

            tree.Add(5);

            // Act
            bool result = tree.Contains(2);

            // Assert
            Assert.False(result);
        }
Exemplo n.º 39
0
        public void TestAddSortedValues()
        {
            var tree  = new BinarySearchTree <int, int>();
            var array = new int[n];

            for (int i = 0; i < n; i++)
            {
                array[i] = i;
                tree.Add(i, i);
            }

            CollectionAssert.AreEqual(array, (ICollection)tree.Keys);
        }
Exemplo n.º 40
0
        public void BinarySearchTreeCanAddLeftChild()
        {
            //Arrange
            BinarySearchTree bst   = new BinarySearchTree();
            Node             node5 = new Node(5);
            Node             node4 = new Node(4);

            //Act
            bst.Add(node5, node4);

            //Assert
            Assert.Equal(node4, node5.LeftChild);
        }
        public void BinarySearchTreeAddMethodTest()
        {
            BinarySearchTree <int> binTree = new BinarySearchTree <int>(Comparer <int> .Default, new List <int> {
                1, 2, 3
            });

            binTree.Add(5);
            CollectionAssert.AreEqual(
                binTree.DirectBypass().ToList(),
                new BinarySearchTree <int>(Comparer <int> .Default, new List <int> {
                1, 2, 3, 5
            }).DirectBypass().ToList());
        }
        public void BinaryTree_Create_DefaultStringComparer_Preoder_Test()
        {
            string[] result = { "adcd", "dfge", "rt", "rtyeuyyu", "aaaaa" };

            BinarySearchTree <string> binarySearchTree = new BinarySearchTree <string>(null);

            binarySearchTree.Add("adcd");
            binarySearchTree.Add("dfge");
            binarySearchTree.Add("aaaaa");
            binarySearchTree.Add("rt");
            binarySearchTree.Add("rtyeuyyu");

            string[] array = new string[5];
            var      i     = 0;

            foreach (var node in binarySearchTree.Preorder)
            {
                array[i++] = node;
            }

            CollectionAssert.AreEqual(array, result);
        }
        public int Count_IntegerTreeWithComparer_TreeCount(int[] nodes)
        {
            var comparer = Comparer <int> .Create((x, y) => x.ToString().Length - y.ToString().Length);

            var tree = new BinarySearchTree <int>(comparer, BinarySearchTree <int> .Traversal.PreOrder);

            foreach (var node in nodes)
            {
                tree.Add(node);
            }

            return(tree.Count);
        }
Exemplo n.º 44
0
        public void BinarySearchTreeCanAddRightChild()
        {
            //Arrange
            BinarySearchTree bst   = new BinarySearchTree();
            Node             node5 = new Node(5);
            Node             node6 = new Node(6);

            //Act
            bst.Add(node5, node6);

            //Assert
            Assert.Equal(node6, node5.RightChild);
        }
        public int Count_PointTreeWithComparer_TreeCount(int[] nodesX, int[] nodesY)
        {
            var comparer = Comparer <Point> .Create((x, y) => x.Y - y.Y);

            var tree = new BinarySearchTree <Point>(comparer, BinarySearchTree <Point> .Traversal.PreOrder);

            for (int i = 0; i < nodesX.Length; ++i)
            {
                tree.Add(new Point(nodesX[i], nodesY[i]));
            }

            return(tree.Count);
        }
Exemplo n.º 46
0
        public void CanAddNodeToBinarySearchTreeTest()
        {
            // Arrange
            Node             n1 = new Node(10);
            Node             n2 = new Node(5);
            BinarySearchTree binarySearchTree = new BinarySearchTree(n1);

            // Act
            binarySearchTree.Add(n1, n2);

            // Assert
            Assert.Equal(n2, n1.LeftChild);
        }
Exemplo n.º 47
0
        public void Add_InOrderSortPoint_NUnit()
        {
            // Arrange
            Point point1 = new Point()
            {
                X = 3, Y = 2
            };
            Point point2 = new Point()
            {
                X = 510, Y = 3
            };
            Point point3 = new Point()
            {
                X = 21, Y = 4
            };

            var comparer = new CustomPoint();

            var binaryTree = new BinarySearchTree <Point>(comparer.Compare);

            var result = new Point[3];

            Point[] expected = { point1, point3, point2 };

            // Act
            binaryTree.Add(point1);
            binaryTree.Add(point2);
            binaryTree.Add(point3);

            int i = 0;

            foreach (var item in binaryTree)
            {
                result[i++] = item;
            }

            // Assert
            Assert.AreEqual(expected, result);
        }
Exemplo n.º 48
0
    static object Solve()
    {
        var n  = int.Parse(Console.ReadLine());
        var a  = Read();
        var qc = int.Parse(Console.ReadLine());
        var qs = Array.ConvertAll(new bool[qc], _ => int.Parse(Console.ReadLine()));

        var set = new BinarySearchTree <int>(a);

        set.Add(-1 << 30);
        set.Add(int.MaxValue);

        return(string.Join("\n", qs.Select(GetMin)));

        int GetMin(int bv)
        {
            var av2 = set.GetMin(x => x >= bv);
            var av1 = set.GetPrevious(av2);

            return(Math.Min(av2 - bv, bv - av1));
        }
    }
Exemplo n.º 49
0
        public void BinaryTree_Create_CustomIntComparer_Postoder_Test()
        {
            int[] result = { -5, 10, 8, 3, 1 };

            BinarySearchTree <int> binarySearchTree = new BinarySearchTree <int>(new ComparerIntCustom());

            binarySearchTree.Add(1);
            binarySearchTree.Add(3);
            binarySearchTree.Add(-5);
            binarySearchTree.Add(8);
            binarySearchTree.Add(10);

            int[] array = new int[5];
            var   i     = 0;

            foreach (var node in binarySearchTree.Postoder)
            {
                array[i++] = node;
            }

            CollectionAssert.AreEqual(array, result);
        }
        public void CanAddRootToEmptyBST()
        {
            //Arrange
            BinarySearchTree <int> testBST = new BinarySearchTree <int>();

            //Act
            int rootValue = 500;

            testBST.Add(rootValue);

            //Assert
            Assert.Equal(rootValue, testBST.Root.Value);
        }
Exemplo n.º 51
0
        public void BinaryTree_Create_DefaultIntComparer_Preoder_Test()
        {
            int[] result = { 1, 3, 8, 10, -5 };

            BinarySearchTree <int> binarySearchTree = new BinarySearchTree <int>(null);

            binarySearchTree.Add(1);
            binarySearchTree.Add(3);
            binarySearchTree.Add(-5);
            binarySearchTree.Add(8);
            binarySearchTree.Add(10);

            int[] array = new int[5];
            var   i     = 0;

            foreach (var node in binarySearchTree.Preorder)
            {
                array[i++] = node;
            }

            CollectionAssert.AreEqual(array, result);
        }
Exemplo n.º 52
0
        public void BinaryTree_Create_StructComparer_Inorder_Test()
        {
            Point[] result = { new Point(7, 8), new Point(3, 4), new Point(1, 2), new Point(-1, 3), new Point(-4, 2) };

            BinarySearchTree <Point> binarySearchTree = new BinarySearchTree <Point>(new ComparerStruct());

            binarySearchTree.Add(new Point(1, 2));
            binarySearchTree.Add(new Point(3, 4));
            binarySearchTree.Add(new Point(-1, 3));
            binarySearchTree.Add(new Point(-4, 2));
            binarySearchTree.Add(new Point(7, 8));

            Point[] array = new Point[5];
            var     i     = 0;

            foreach (var node in binarySearchTree.Inorder)
            {
                array[i++] = node;
            }

            CollectionAssert.AreEqual(array, result);
        }
        public void BinaryTree_LevelOrder_Test()
        {
            var tree1 = new BinarySearchTree<int>();
            tree1.Add(24);
            tree1.Add(12);
            tree1.Add(15);
            tree1.Add(67);
            tree1.Add(32);
            tree1.Add(13);
            tree1.Add(89);
            tree1.Add(9);

            Console.WriteLine("LevelOrder traversal");
            tree1.LevelOrder(tree1.Root);
        }
        public void BinaryTree_Tests()
        {
            var tree1 = new BinarySearchTree<int>();
            tree1.Add(24);
            tree1.Add(12);
            tree1.Add(15);
            tree1.Add(67);
            tree1.Add(32);
            tree1.Add(13);
            tree1.Add(89);
            tree1.Add(9);

            var tree2 = new BinarySearchTree<int>();
            tree2.Add(24);
            tree2.Add(12);
            tree2.Add(15);
            tree2.Add(67);
            tree2.Add(32);
            tree2.Add(13);
            tree2.Add(89);
            tree2.Add(9);

            Console.WriteLine("Inorder traversal resulting Tree Sort");
            tree1.Inorder(tree1.Root);
            Console.WriteLine(" ");

            Console.WriteLine();
            Console.WriteLine("Preorder traversal");
            tree1.Preorder(tree1.Root);
            Console.WriteLine(" ");

            Console.WriteLine();
            Console.WriteLine("Postorder traversal");
            tree1.Postorder(tree1.Root);
            Console.WriteLine(" ");

            //Assert.IsTrue(tree1.PathSum(tree1.Root(), 45));
            //Assert.IsTrue(tree1.PathSum(tree1.Root(), 51));
            //Assert.IsFalse(tree1.PathSum(tree1.Root(), 42));

            //Assert.AreEqual(8, tree1.Size(tree1.Root()));

            //Assert.AreEqual(9, tree1.Minimum(tree1.Root()));

            //Assert.AreEqual(89, tree1.Maximum(tree1.Root()));

            //Assert.IsTrue(BinaryTree.AreTwoTreesEqual(tree1.Root(), tree2.Root()));
        }
Exemplo n.º 55
0
        public void Simple()
        {
            var tree = new BinarySearchTree<int, string>();

            for (var i = 20; i > 10; i--)
            {
                tree.Add(i, i.ToString());
            }

            for (var i = 0; i <= 10; i++)
            {
                tree.Add(i, i.ToString());
            }

            var keys = tree.Keys;

            for (var i = 0; i <= 20; i++)
            {
                Assert.IsTrue(keys.Contains(i));
            }

            Assert.AreEqual(keys.Count, 21);
        }
Exemplo n.º 56
0
        /// <summary>
        /// To check if give tree is balanced
        /// </summary>
        public void Run()
        {

            BinarySearchTree<int> newTreeUnbalanced = new BinarySearchTree<int>();
            newTreeUnbalanced.Add(7);
            newTreeUnbalanced.Add(8);
            newTreeUnbalanced.Add(5);
            newTreeUnbalanced.Add(6);
            newTreeUnbalanced.Add(14);
            newTreeUnbalanced.Add(11);
            newTreeUnbalanced.Add(9);
            newTreeUnbalanced.Add(12);
            newTreeUnbalanced.Add(10);
            newTreeUnbalanced.Add(17);
              //             7
              //        5         8
              //      x   6      x   14
              //         x  x      11  17
              //                9    12
              //               x  10

            VisitNode(newTreeUnbalanced.Root);
        }
Exemplo n.º 57
0
        static void Main(string[] args)
        {
            BinarySearchTree<int> tree1 = new BinarySearchTree<int>();

            // test the add method
            tree1.Add(2);
            tree1.Add(1);
            tree1.Add(3);
            tree1.Add(7);
            tree1.Add(5);

            // test the Clone() method
            BinarySearchTree<int> tree2 = (BinarySearchTree<int>)tree1.Clone();

            // test the ToString() method
            Console.WriteLine("Tree 1: {0}", tree1);
            Console.WriteLine("Tree 2: {0}", tree2);

            // test the Equals() method
            Console.WriteLine("The two trees are equal: {0}",
                (tree1 == tree2));

            // test the Delete() method
            tree2.Delete(7);
            Console.WriteLine("After deleting 5 from tree 2: {0}", tree2);

            // test the Find() method
            var node = tree1.Find(3);
            if(node != null)
            {
                Console.WriteLine("3 was found in tree 1");
            }
            else
            {
                Console.WriteLine("3 was NOT found in tree 1");
            }
        }
        public void BinaryTreeAlgorithms_Test()
        {
            var tree1 = new BinarySearchTree<int>();
            tree1.Add(24);
            tree1.Add(12);
            tree1.Add(15);
            tree1.Add(67);
            tree1.Add(32);
            tree1.Add(13);
            tree1.Add(89);
            tree1.Add(9);

            tree1.Remove(13);
            tree1.Remove(24);
            //Assert.IsTrue(tree1.PathSum(tree1.Root(), 45));
            //Assert.IsTrue(tree1.PathSum(tree1.Root(), 51));
            //Assert.IsFalse(tree1.PathSum(tree1.Root(), 42));

            //Assert.AreEqual(8, tree1.Size(tree1.Root()));

            //Assert.AreEqual(9, tree1.Minimum(tree1.Root()));

            //Assert.AreEqual(89, tree1.Maximum(tree1.Root()));

            //Assert.IsTrue(BinaryTree.AreTwoTreesEqual(tree1.Root(), tree2.Root()));

            Console.WriteLine("Inorder traversal ");
            tree1.Inorder(tree1.Root);
            Console.WriteLine(" ");

            TreeAlgorithms<int>.Mirror(tree1.Root);

            Console.WriteLine("Inorder traversal of the Mirror tree");
            tree1.Inorder(tree1.Root);
            Console.WriteLine(" ");

            Console.WriteLine();
            Console.WriteLine("Preorder traversal");
            tree1.Preorder(tree1.Root);
            Console.WriteLine(" ");

            Console.WriteLine();
            Console.WriteLine("Postorder traversal");
            tree1.Postorder(tree1.Root);
            Console.WriteLine(" ");
        }
        private static void RunBST()
        {
            var values = new[] { 15, 6, 20, 3, 7, 17, 19, 22, 2, 4, 13, 9 };

            Console.WriteLine($"Building binary tree from: {Utils.FormatArray(values)} =>\n");

            var tree = new BinarySearchTree<int>();
            foreach (var v in values)
            {
                tree.Add(v);
            }

            Utils.PrintBinaryTree(tree.Root);

            Console.WriteLine($"Minimum : {tree.Minimum().Value}");
            Console.WriteLine($"Maximum : {tree.Maximum().Value}");

            var searchValues = new[] { 9, 3, 100, 20, 2 };
            Console.WriteLine($"Searching values {Utils.FormatArray(searchValues)}");
            foreach(var v in searchValues)
            {
                var node = tree.Search(v);
                Console.Write("The tree {0} value {1}. ",
                    node == null ? "does not contain" : "contains", v);

                if (node != null)
                {
                    var successor = BinarySearchTree<int>.Successor(node);
                    Console.Write("Successor {0}. ", successor != null ? successor.Value.ToString() : "N/A");
                    var predecessor = BinarySearchTree<int>.Predecessor(node);
                    Console.Write("Predecessor {0}.", predecessor != null ? predecessor.Value.ToString() : "N/A");
                }

                Console.WriteLine();
            }

            var deleteValues = new [] { 15 };
            foreach (var v in deleteValues)
            {
                var node = tree.Search(v);
                Console.WriteLine($"Deleting value: {v}");
                tree.Delete(node);
                Utils.PrintBinaryTree(tree.Root);
                Console.WriteLine();
            }
        }
        public void BinaryTreeAlgorithms_Mirror_Test()
        {
            var tree1 = new BinarySearchTree<int>();
            tree1.Add(24);
            tree1.Add(12);
            tree1.Add(15);
            tree1.Add(67);
            tree1.Add(32);
            tree1.Add(13);
            tree1.Add(89);
            tree1.Add(9);

            Console.WriteLine("Inorder traversal ");
            tree1.Inorder(tree1.Root);
            Console.WriteLine(" ");

            TreeAlgorithms<int>.Mirror(tree1.Root);

            Console.WriteLine("Inorder traversal of the Mirror tree");
            tree1.Inorder(tree1.Root);
            Console.WriteLine(" ");
        }