private static void TestBinarySearchTree()
        {
            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());
        }
Exemple #2
0
        public static void Main(string[] args)
        {
            /*
             *
             *
             *                          7
             *                         / \
             *                        3   13
             *                       / \  / \
             *                      2  4  9  16
             *                     /          \
             *                    1            19
             *
             */

            BinarySearchTree BST = new BinarySearchTree();

            /*
             *
             * BST.Insert(BST.GetRoot(),4);
             * BST.Insert(BST.GetRoot(),7);
             * BST.Insert(BST.GetRoot(),16);
             * BST.Insert(BST.GetRoot(),19);
             * BST.Insert(BST.GetRoot(),3);
             * BST.Insert(BST.GetRoot(),1);
             * BST.Insert(BST.GetRoot(),9);
             * BST.Insert(BST.GetRoot(),2);
             *
             */
            BST.InsertBST(6);
            BST.InsertBST(4);
            BST.InsertBST(9);
            BST.InsertBST(2);
            BST.InsertBST(5);
            BST.InsertBST(8);
            BST.InsertBST(12);
            BST.InsertBST(10);
            BST.InsertBST(14);
            Console.WriteLine(Environment.NewLine);
            int searchValue = 9;

            Console.WriteLine($"Searching for Value {searchValue} in the tree.. ");

            if (BinarySearchTree.Search(BST.GetRoot(), searchValue) != null)
            {
                Console.WriteLine($"Value {searchValue} found!!");
            }
            else
            {
                Console.WriteLine($"Value {searchValue} not found!!");
            }

            List <int> result = new List <int>();

            // Node root = BinarySearchTree.CreateTree();
            Console.WriteLine(Environment.NewLine);
            Console.WriteLine("InOrder Traversal: ");
            BinarySearchTree.InOrder(BST.GetRoot(), result);
            Console.WriteLine(string.Join(" ", result));

            Console.WriteLine(Environment.NewLine);
            Console.WriteLine("Delete 2");
            Console.WriteLine(BST.Delete(BST.GetRoot(), 2));
            Console.WriteLine("After deletion");
            result.Clear();
            Console.WriteLine("InOrder Traversal: ");
            BinarySearchTree.InOrder(BST.GetRoot(), result);
            Console.WriteLine(string.Join(" ", result));

            Console.WriteLine(Environment.NewLine);
            Console.WriteLine("PreOrder Traversal: ");
            BinarySearchTree.PreOrder(BST.GetRoot());

            Console.WriteLine(Environment.NewLine);
            Console.WriteLine("PostOrder Traversal: ");
            BinarySearchTree.PostOrder(BST.GetRoot());

            Console.WriteLine(Environment.NewLine);
            Console.WriteLine("Find Minimum Value in Binary Search Tree: ");
            int min = BinarySearchTree.FindMinimum(BST.GetRoot());

            Console.WriteLine($"Minimum value in Binary Search tree is:  {min}");


            Console.WriteLine(Environment.NewLine);
            Console.WriteLine("Find Maximum Value in Binary Search Tree: ");
            int max = BinarySearchTree.FindMaxium(BST.GetRoot());

            Console.WriteLine($"Maximum value in Binary Search tree is:  {max}");

            Console.WriteLine(Environment.NewLine);
            Console.WriteLine("Find kth Maximum Value in Binary Search Tree: ");
            int k    = 3;
            int kmax = BinarySearchTree.FindKMaxium(BST.GetRoot(), k);

            Console.WriteLine($"kth Maximum: k={k} value in Binary Search tree is:  {kmax}");

            int k1 = 10;

            Console.WriteLine(Environment.NewLine);
            Console.WriteLine($"Find Ancestors of Node k: {k1} in Binary Search Tree: ");
            Console.WriteLine(BinarySearchTree.FindAncestors(BST.GetRoot(), k1));

            Console.WriteLine($"Height of Binary Search tree is: {BinarySearchTree.FindHeight(BST.GetRoot())}");

            int k2 = 3;

            Console.WriteLine($"Binary Search Tree Nodes at k: {k2} distance");
            Console.WriteLine(BinarySearchTree.FindKNodes(BST.GetRoot(), k2));
        }
Exemple #3
0
        //Driver method to test
        static void Main(string[] args)
        {
            BinarySearchTree tree = new BinarySearchTree();

            /* Let us create following BST
             *    50
             * /     \
             * 30      70
             * /  \    /  \
             * 20   40  60   80 */

            tree.Insert(50);
            tree.Insert(30);
            tree.Insert(20);
            tree.Insert(40);
            tree.Insert(70);
            tree.Insert(60);
            tree.Insert(80);

            tree.PrintBST();


            /* Delete in BST
             *
             *        50                            50
             *     /     \         delete(20)      /   \
             *    30      70       --------->    30     70
             *   /  \    /  \                     \    /  \
             * 20   40  60   80                   40  60   80
             *
             *
             *
             *        50                            50
             *     /     \         delete(30)      /   \
             *    30      70       --------->    40     70
             \    /  \                          /  \
             \      40  60   80                       60   80
             \
             \
             \
             \        50                            60
             \     /     \         delete(50)      /   \
             \    40      70       --------->    40    70
             \           /  \                            \
             \          60   80                           80
             \
             */

            Console.WriteLine("\nDelete 20");
            tree.Delete(20);
            Console.WriteLine("Inorder traversal of the modified tree");
            tree.PrintBST();

            Console.WriteLine("\nDelete 30");
            tree.Delete(30);
            Console.WriteLine("Inorder traversal of the modified tree");
            tree.PrintBST();

            Console.WriteLine("\nDelete 50");
            tree.Delete(50);
            Console.WriteLine("Inorder traversal of the modified tree");
            tree.PrintBST();


            Console.ReadKey();
        }
Exemple #4
0
        static void Main(string[] args)
        {
            BinarySearchTree bt = new BinarySearchTree();
            int choice, x;

            while (true)
            {
                WriteLine();
                WriteLine("1. Display Tree");
                WriteLine("2. Search");
                WriteLine("3. Add a New Node");
                WriteLine("4. Delete a Node");
                WriteLine("5. Preorder Traversal");
                WriteLine("6. Inorder Traversal");
                WriteLine("7. Postorder Traversal");
                WriteLine("8. Height of Tree");
                WriteLine("9. Find Minimum Key");
                WriteLine("10. Find Maximum Key");
                WriteLine("11. Quit");

                Write("Please enter your selection: ");
                choice = Convert.ToInt32(ReadLine());
                WriteLine();

                if (choice == 11)
                {
                    break;
                }

                switch (choice)
                {
                case 1:
                    bt.Display();
                    break;

                case 2:
                    Write("Enter the key to be searched: ");
                    x = Convert.ToInt32(ReadLine());

                    if (bt.Search(x))
                    {
                        WriteLine("Key found.");
                    }
                    else
                    {
                        WriteLine("Key not found.");
                    }
                    break;

                case 3:
                    Write("Enter the key to be inserted: ");
                    x = Convert.ToInt32(ReadLine());
                    bt.Insert(x);
                    break;

                case 4:
                    Write("Enter the key to be deleted: ");
                    x = Convert.ToInt32(ReadLine());
                    bt.Delete(x);
                    break;

                case 5:
                    bt.Preorder();
                    break;

                case 6:
                    bt.Inorder();
                    break;

                case 7:
                    bt.Postorder();
                    break;

                case 8:
                    WriteLine($"Height of tree is {bt.Height()}");
                    break;

                case 9:
                    WriteLine($"Minimum key is {bt.Min()}");
                    break;

                case 10:
                    WriteLine($"Maximum key is {bt.Max()}");
                    break;

                default:
                    WriteLine("Please make a valid selection.");
                    break;
                }
            }
        }
        public static void Main()
        {
            BinarySearchTree tree = new BinarySearchTree();

            Random r = new Random();

            WriteLine("Welcome! The purpose of this program is to generate numbers randomly " +
                      "\nand use a binary search tree to sort and find any given number.");
            string userInput = ReadLine();

            for (int index = 0; index < 13; index++)
            {
                int generated = r.Next(0, 100);
                tree.Insert(generated);
            }

            Write("Would you like to traverse in-order? \"No\" skips. ");
            userInput = ReadLine();

            if (!string.Equals(userInput, "No", StringComparison.OrdinalIgnoreCase))
            {
                tree.Inorder();
            }

            Write("Would you like to traverse pre-order? \"No\" skips. ");
            userInput = ReadLine();

            if (!string.Equals(userInput, "No", StringComparison.OrdinalIgnoreCase))
            {
                tree.Preorder();
            }

            Write("Would you like to traverse post-order? \"No\" skips. ");
            userInput = ReadLine();

            if (!string.Equals(userInput, "No", StringComparison.OrdinalIgnoreCase))
            {
                tree.Postorder();
            }

            Write("Would you like to print the smallest number? \"No\" skips. ");
            userInput = ReadLine();

            if (!string.Equals(userInput, "No", StringComparison.OrdinalIgnoreCase))
            {
                tree.Minimum();
            }

            Write("Would you like to print the largest number? \"No\" skips. ");
            userInput = ReadLine();

            if (!string.Equals(userInput, "No", StringComparison.OrdinalIgnoreCase))
            {
                tree.Maximum();
            }

            Write("Would you like to search for a particular number? \"Yes\" continues. ");
            userInput = ReadLine();

            if (string.Equals(userInput, "Yes", StringComparison.OrdinalIgnoreCase))
            {
                Write("Please enter a number to search for: ");
                int number = int.Parse(ReadLine());
                tree.Contains(number);
            }

            Write("Would you like to delete a particular number? \"Yes\" continues. ");
            userInput = ReadLine();

            if (string.Equals(userInput, "Yes", StringComparison.OrdinalIgnoreCase))
            {
                Write("Please enter a number to delete: ");
                int number = int.Parse(ReadLine());
                tree.Delete(number);
            }

            tree.Inorder();
        }
Exemple #6
0
        static void Main()
        {
            try
            {
                #region Test1: Creating of nodes

                Console.ForegroundColor = ConsoleColor.Yellow;
                Console.WriteLine("Test1: Creating of nodes");
                Console.ResetColor();
                Console.Write("Press any key to start the test...");
                Console.ReadKey();

                // Creates new empty tree
                var tree = new BinarySearchTree<int>();
                Console.WriteLine("\n\nA new tree was created...");

                // Adds some nodes in the tree
                Thread.Sleep(1500);
                tree.Add(2);
                tree.Add(7);
                tree.Add(1);
                tree.Add(5);
                tree.Add(22);
                tree.Add(-7);
                tree.Add(4);
                Console.WriteLine("{0} nodes were added in the tree.\n", tree.Nodes.Count);

                // Prints the tree
                Thread.Sleep(1500);
                Console.Write("The tree: ");
                Console.ForegroundColor = ConsoleColor.Gray;
                Console.WriteLine(tree);
                Console.ResetColor();

                // Prints the nodes of the tree
                Thread.Sleep(1500);
                for (int i = 0; i < tree.Nodes.Count; i++)
                {
                    Console.Write("Node{0}: ", i);
                    Console.ForegroundColor = ConsoleColor.Gray;
                    Console.WriteLine("{0}", tree.Nodes[i]);
                    Console.ResetColor();
                    Thread.Sleep(400);
                }

                #endregion

                #region Test2: Searching

                Console.ForegroundColor = ConsoleColor.Yellow;
                Console.WriteLine("\nTest2: Searching");
                Console.ResetColor();
                Console.Write("Press any key to start the test...");
                Console.ReadKey();

                // Search for some node in the tree
                Console.WriteLine();
                TreeNodeSearch(tree, 2);
                TreeNodeSearch(tree, 7);
                TreeNodeSearch(tree, 14);
                TreeNodeSearch(tree, 22);

                #endregion

                #region Test3: Cloning

                Console.ForegroundColor = ConsoleColor.Yellow;
                Console.WriteLine("\nTest3: Cloning");
                Console.ResetColor();
                Console.Write("Press any key to start the test...");
                Console.ReadKey();

                // Cloning of the tree
                var clone = tree.Clone() as BinarySearchTree<int>;
                Console.WriteLine("\n\nA clone was created...");

                // Prints the clone
                Thread.Sleep(1500);
                Console.Write("The clone: ");
                Console.ForegroundColor = ConsoleColor.Gray;
                Console.WriteLine(clone);
                Console.ResetColor();

                // Cloning check
                TreeCloningCheck(tree, clone, false);

                #endregion

                #region Test4: Deleting

                Console.ForegroundColor = ConsoleColor.Yellow;
                Console.WriteLine("\nTest4: Deleting");
                Console.ResetColor();
                Console.Write("Press any key to start the test...");
                Console.ReadKey();

                // Delete two nodes from the tree
                tree.Delete(2);
                tree.Delete(5);
                Console.WriteLine("\n\nTwo nodes with value 2 and 5 were deleted from the tree.");

                // Prints the tree
                Thread.Sleep(1500);
                Console.Write("\nThe tree: ");
                Console.ForegroundColor = ConsoleColor.Gray;
                Console.WriteLine(tree);
                Console.ResetColor();
                Thread.Sleep(1000);
                Console.Write("The clone: ");
                Console.ForegroundColor = ConsoleColor.Gray;
                Console.WriteLine(clone);
                Console.ResetColor();

                // Cloning check
                TreeCloningCheck(tree, clone, true);

                // Gets a HashCode for the tree
                Thread.Sleep(1500);
                Console.WriteLine("\nThe HashCode for the tree: {0}", tree.GetHashCode());

                // Gets a HashCode for the clone
                Thread.Sleep(1000);
                Console.WriteLine("The HashCode for the clone: {0}\n", clone.GetHashCode());

                #endregion
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
Exemple #7
0
        static void Main(string[] args)
        {
            var bt = new BinarySearchTree();
            int x;

            while (true)
            {
                Console.WriteLine("1. Display tree");
                Console.WriteLine("2. Search");
                Console.WriteLine("3. Insert a new node");
                Console.WriteLine("4. Delete a node");
                Console.WriteLine("5. PreOrder Traversal");
                Console.WriteLine("6. InOrder Traversal");
                Console.WriteLine("7. PostOrder Traversal");
                Console.WriteLine("8. Height of tree");
                Console.WriteLine("9. Find Minimum key");
                Console.WriteLine("10. Find Maximum key");
                Console.WriteLine("11. Quit");

                var choice = Convert.ToInt32(Console.ReadLine());

                if (choice == 11)
                {
                    break;
                }

                switch (choice)
                {
                case 1:
                    bt.Display();
                    break;

                case 2:
                    Console.Write("Enter a key to be searched : ");
                    x = Convert.ToInt32(Console.ReadLine());

                    Console.WriteLine(bt.Search(x) ? "Key was found" : "Key not found");
                    break;

                case 3:
                    Console.Write("Enter a key to be Inserted : ");
                    x = Convert.ToInt32(Console.ReadLine());
                    bt.Insert(x);
                    break;

                case 4:
                    Console.Write("Enter a key to be Deleted : ");
                    x = Convert.ToInt32(Console.ReadLine());
                    bt.Delete(x);
                    break;

                case 5:
                    bt.PreOrder();
                    break;

                case 6:
                    bt.InOrder();
                    break;

                case 7:
                    bt.PostOrder();
                    break;

                case 8:
                    Console.WriteLine($"The HEIGHT of the tree is : {bt.Height()}");
                    break;

                case 9:
                    Console.WriteLine($"The MINIMUM key is : {bt.Min()}");
                    break;

                case 10:
                    Console.WriteLine($"The MAXIMUM key is : {bt.Max()}");
                    break;

                default:
                    Console.WriteLine("Invalid selection entered!!!");
                    break;
                }
            }
        }
Exemple #8
0
        static void Main(string[] args)
        {
            BinarySearchTree bt = new BinarySearchTree();
            int choice, x;

            while (true)
            {
                Console.WriteLine("1.Display Tree");
                Console.WriteLine("2.Search");
                Console.WriteLine("3.Insert a new node");
                Console.WriteLine("4.Delete a node");
                Console.WriteLine("5.Preorder Traversal");
                Console.WriteLine("6.Inorder Traversal");
                Console.WriteLine("7.Postorder Traversal");
                Console.WriteLine("8.Height of tree");
                Console.WriteLine("9.Find Minimum key");
                Console.WriteLine("10.Find Maximum key");
                Console.WriteLine("11.Quit");
                Console.Write("Enter your choice:");
                choice = Convert.ToInt32(Console.ReadLine());
                if (choice == 11)
                {
                    break;
                }
                switch (choice)
                {
                case 1:
                    bt.Display();
                    break;

                case 2:
                    Console.Write("Enter the key to be searched:");
                    x = Convert.ToInt32(Console.ReadLine());
                    if (bt.Search(x))
                    {
                        Console.WriteLine("Key found");
                    }
                    else
                    {
                        Console.WriteLine("key not found");
                    }
                    break;

                case 3:
                    Console.Write("Enter the key to be inserted:");
                    x = Convert.ToInt32(Console.ReadLine());
                    bt.Insert(x);
                    break;

                case 4:
                    Console.Write("Enter the key to be deleted:");
                    x = Convert.ToInt32(Console.ReadLine());
                    bt.Delete(x);
                    break;

                case 5:
                    bt.PreOrder();
                    break;

                case 6:
                    bt.InOrder();
                    break;

                case 7:
                    bt.PostOrder();
                    break;

                case 8:
                    Console.WriteLine("Height of tree is " + bt.Height());
                    break;

                case 9:
                    Console.WriteLine("Minimum key is " + bt.Min());
                    break;

                case 10:
                    Console.WriteLine("Maximum key is " + bt.Max());
                    break;
                }
            }
        }