/// <summary>
        /// Metho to Search node in binary search tree
        /// </summary>
        /// <param name="element"></param>
        /// <param name="node"></param>
        /// <returns></returns>
        public bool Search(T element, BST <T> node)
        {
            if (node == null)
            {
                return(false);
            }
            if (node.NodeData.Equals(element))
            {
                // Console.WriteLine("Found the element in BST" + " " + node.NodeData);
                result = true;
            }

            else if (node.NodeData.CompareTo(element) < 0)
            {
                Search(element, node.RightTree);
            }
            else
            {
                Search(element, node.LeftTree);
            }
            return(result);
        }
        /// <summary>
        /// Reads binary data from a file to construct a BST object
        /// </summary>
        /// <param name="TreeStoreFile"></param>
        /// <returns></returns>
        public BST ReadBSTFromFile(string TreeStoreFile)
        {
            try
            {
                //Make sure that a file exists
                if (!File.Exists(TreeStoreFile))
                {
                    File.Create(TreeStoreFile);
                }

                BST             bst = new BST();
                Stream          DeserializationFileStream = File.OpenRead(TreeStoreFile);
                BinaryFormatter deserializer = new BinaryFormatter();
                bst = (BST)deserializer.Deserialize(DeserializationFileStream);
                DeserializationFileStream.Close();

                return(bst);
            }
            catch
            {
                throw new Exception("Some error occured while reading tree data from file");
            }
        }
Exemple #3
0
        public BST Insert(int value)
        {
            Stack <BST> stack = new Stack <BST>();

            stack.Push(this);

            while (stack.Count > 0)
            {
                BST node = stack.Pop();

                if (value < node.value)
                {
                    if (node.left != null)
                    {
                        stack.Push(node.left);
                    }
                    else
                    {
                        node.left = new BST(value);
                    }
                }
                else
                {
                    if (node.right != null)
                    {
                        stack.Push(node.right);
                    }
                    else
                    {
                        node.right = new BST(value);
                    }
                }
            }

            return(this);
        }
Exemple #4
0
        static void Main(string[] args)
        {
            var random = new Random();
            var bst    = new BST();
            var list   = new List <int>();

            for (int i = 0; i < 100; i++)
            {
                list.Add(random.Next(1, 200));
            }
            foreach (var item in list)
            {
                bst.Insert(item);
            }
            bst.Inorder();
            Console.ReadKey();

            foreach (var item in list)
            {
                bst.Delete(item);
            }
            bst.Inorder();
            Console.ReadKey();
        }
Exemple #5
0
 public void Dispose()
 {
     parent   = null;
     nCurrent = null;
     qNodes   = null;
 }
Exemple #6
0
 public BreadthFirstEnumerator(BST <T> parent)
 {
     this.parent = parent;
     Reset();
 }
        static void Main(string[] args)
        {
            try
            {
                ObjectPersistence persister     = new ObjectPersistence();
                const string      TreeStoreFile = @"D:\SavedTree.bin";

                #region Construct the tree

                Console.WriteLine("Constructing tree...\t");

                BST bst = new BST();
                bst.Insert(20);
                bst.Insert(25);
                bst.Insert(45);
                bst.Insert(15);
                bst.Insert(67);
                bst.Insert(43);
                bst.Insert(80);
                bst.Insert(33);
                bst.Insert(67);
                bst.Insert(99);
                bst.Insert(91);

                #endregion

                #region Traverse the tree

                Console.WriteLine(@"----------------------------------------------------
Before serialization and de-serialization");

                Console.WriteLine("\nInorder Traversal (Left - Root - Right):");
                bst.Inorder(bst.GetRoot());
                Console.WriteLine("\nPreorder Traversal (Root - Left - Right): ");
                bst.Preorder(bst.GetRoot());
                Console.WriteLine("\nPostorder Traversal (Left - Right - Root): ");
                bst.Postorder(bst.GetRoot());

                #endregion

                #region Serialize and de-serialize the tree to and from a file

                Console.WriteLine(@"
----------------------------------------------------
Storing (serializing) tree to file...");

                persister.StoreBSTToFile(bst, TreeStoreFile);

                Console.WriteLine(string.Format("Tree saved to {0} in binary format\nDe-serializing in process...\t", TreeStoreFile));

                bst = persister.ReadBSTFromFile(TreeStoreFile);

                Console.WriteLine("\nAfter serialization and de-serialization");

                Console.WriteLine("\nInorder Traversal (Left - Root - Right):");
                bst.Inorder(bst.GetRoot());
                Console.WriteLine("\nPreorder Traversal (Root - Left - Right): ");
                bst.Preorder(bst.GetRoot());
                Console.WriteLine("\nPostorder Traversal (Left - Right - Root): ");
                bst.Postorder(bst.GetRoot());

                #endregion

                #region Finding maximum, minimum and size of BST

                Console.WriteLine(@"
----------------------------------------------------
Other details of the tree");

                Console.WriteLine("Minimum value in the tree: " + bst.GetMinimum(bst.GetRoot()));

                Console.WriteLine("Maximum value in the tree: " + bst.GetMaximum(bst.GetRoot()));

                Console.WriteLine("Size of the tree: " + bst.GetSize(bst.GetRoot()));

                #endregion
            }
            catch (Exception ex)
            {
                Console.WriteLine("Oops!\n" + ex.Message);
            }

            //Keep the console running

            Console.WriteLine("\nPRESS ENTER TO TERMINATE...");
            Console.ReadLine();
        }
Exemple #8
0
 static void TestClear(BST <int> bst)
 {
     bst.Clear();
     Console.WriteLine("Tree Contents after Clear: " + bst.ToString());
     Console.WriteLine("Count: " + bst.Count);
 }
Exemple #9
0
 static void TestIterate(BST <int> bst)
 {
     bst.Iterate(DoSomethingToAnInt, TraversalOrder.PRE_ORDER);
 }
Exemple #10
0
        public static void Main(string[] args)
        {
            var algorithm = new Algorithm();

            //int sum = 0;
            //int i = 0;
#if SKOLA
            foreach (var line in File.ReadLines("dictionary.txt"))
#endif
#if MOJE
            foreach (var line in File.ReadLines("myDictionary.txt"))
#endif
            {
                var word = Word.FromLine(line);
                algorithm.Add(word);

                //sum += word.Count;
                //i++;
                //Console.WriteLine($"{i} -> {sum} -> {word.Count} -> {word.Probability}");
            }

            foreach (var dummy in algorithm.Dummies)
            {
                algorithm.AddDummyToKey(dummy);
            }

            algorithm.FillEmptyDummiesForKeys();

            //Console.WriteLine(sum);

            //var s = 0;
            //foreach (var key in algorithm.Keys)
            //{
            //    Console.WriteLine($"{key} -> {string.Join(", ", algorithm.KeyDummies[s])}");
            //    s++;
            //}
            //Console.WriteLine($"dn -> {string.Join(", ", algorithm.KeyDummies[algorithm.Keys.Count])}");

            //Console.WriteLine("----------------------");

            //foreach (var dummy in algorithm.Dummies)
            //{
            //    Console.WriteLine(dummy);
            //}
            Console.WriteLine(algorithm.KeyDummies.Values.Sum(v => v.Count));
            var result = algorithm.OptimalBst();

            //var p = new[] { 0.15, 0.10, 0.05, 0.10, 0.20, };
            //var q = new[] { 0.05, 0.10, 0.05, 0.05, 0.05, 0.10, };
            //var result2 = Algorithm.OptimalBst(p, q);

            //foreach (var e in result.Item1)
            //{
            //    foreach (var e2 in e)
            //    {
            //        Console.Write($"{e2}, ");
            //    }

            //    Console.WriteLine();
            //}

            //Console.WriteLine("--------------------------------");

            //foreach (var e in result.Item2)
            //{
            //    foreach (var e2 in e)
            //    {
            //        Console.Write($"{e2}, ");
            //    }

            //    Console.WriteLine();
            //}

            for (var i = 0; i < result.Item2.Length; i++)
            {
                for (var j = 0; j < result.Item2[i].Length; j++)
                {
                    result.Item2[i][j]--;
                }
            }

            //var table = result.Item2;
            //var rootIndex = table[0][table[0].Length - 1];
            //var root = algorithm.Keys[rootIndex];
            //Console.WriteLine(root);
            //var leftIndex = table[0][rootIndex - 1];
            //var left = algorithm.Keys[leftIndex];
            //Console.WriteLine(left);
            //var rightIndex = table[rootIndex + 1][table[0].Length - 1];
            //var right = algorithm.Keys[rightIndex];
            //Console.WriteLine(right);

            var bst = BST.FromTable(algorithm.Keys, algorithm.KeyDummies, result.Item2);
            Console.WriteLine(BSTCost.Calculate(bst));
            Console.WriteLine($"after - {bst.Search("after")}");
            Console.WriteLine($"i - {bst.Search("i")}");
            Console.WriteLine($"if - {bst.Search("if")}");
            Console.WriteLine($"mr - {bst.Search("mr")}");
            Console.WriteLine($"own - {bst.Search("own")}");
            Console.WriteLine($"very - {bst.Search("very")}");
            Console.WriteLine($"year - {bst.Search("year")}");
            Console.WriteLine($"yes - {bst.Search("yes")}");
            Console.WriteLine($"our - {bst.Search("our")}");
            Console.WriteLine($"might - {bst.Search("might")}");
        }
Exemple #11
0
 public DepthFirstEnumerator(BST <T> parent)
 {
     this.parent = parent;
 }
 /// <summary>
 /// constructor and pass parameter
 /// </summary>
 /// <param name="nodeData"></param>
 public BST(T nodeData)
 {
     NodeData  = nodeData;
     LeftTree  = null;
     RightTree = null;
 }
Exemple #13
0
 public StackSorter(MyStack stack)
 {
     this.stack = stack;
     tree       = new BST();
 }
        public static BST FromTable(List <Word> keys, Dictionary <int, List <Word> > keyDummies, int[][] table)
        {
            var stack    = new Queue <Help>();
            var rootHelp = new Help(0, table.Length - 1);

            stack.Enqueue(rootHelp);

            var rootIndex = table[rootHelp.Row][rootHelp.Column];
            var rootItem  = new BSTItem(keys[rootIndex]);
            var bst       = new BST(rootItem);

            keys[rootIndex].Added = true;

            while (stack.Count != 0)
            {
                var current = stack.Dequeue();
                if (current.Row > current.Column)
                {
                    if (keyDummies[current.Row].Count > 0 && !keyDummies[current.Row][0].Added)
                    {
                        bst.Add(new BSTItem(keyDummies[current.Row]));
                        keyDummies[current.Row][0].Added = true;
                    }

                    //if (current.Row < keyDummies.Count - 1)
                    //{
                    //    if (keyDummies[current.Row + 1].Count > 0 && !keyDummies[current.Row + 1][0].Added)
                    //    {
                    //        bst.Add(new BSTItem(keyDummies[current.Row + 1]));
                    //        keyDummies[current.Row + 1][0].Added = true;
                    //    }
                    //}
                    if (keyDummies[current.Column + 1].Count > 0 && !keyDummies[current.Column + 1][0].Added)
                    {
                        bst.Add(new BSTItem(keyDummies[current.Column + 1]));
                        keyDummies[current.Column + 1][0].Added = true;
                    }
                }
                else
                {
                    var currentItemIndex = table[current.Row][current.Column];

                    stack.Enqueue(new Help(current.Row, currentItemIndex - 1));
                    stack.Enqueue(new Help(currentItemIndex + 1, current.Column));

                    if (keys[currentItemIndex].Added)
                    {
                        continue;
                    }

                    //var subBst = new BST(new BSTItem(keys[currentItemIndex]));

                    bst.Add(new BSTItem(keys[currentItemIndex]));
                    keys[currentItemIndex].Added = true;

                    //if (current.Row == current.Column)
                    //{
                    //    subBst.Add(new BSTItem(keyDummies[currentItemIndex]));
                    //    subBst.Add(new BSTItem(keyDummies[currentItemIndex + 1]));
                    //}
                }
            }

            return(bst);
        }