Exemplo n.º 1
0
        public Dictionary<char, int> ЧастотаСимвола = new Dictionary<char, int>();// Частоты символов

        public void Build(string source)
        {
            for (int i = 0; i < source.Length; i++)
            {
                if (!ЧастотаСимвола.ContainsKey(source[i]))
                {
                    ЧастотаСимвола.Add(source[i], 0);
                }

                ЧастотаСимвола[source[i]]++;
            }

            foreach (KeyValuePair<char, int> symbol in ЧастотаСимвола)
            {
                nodes.Add(new Node() { Symbol = symbol.Key, Frequency = symbol.Value });
            }

            while (nodes.Count > 1)
            {
                List<Node> orderedNodes = nodes.OrderBy(node => node.Frequency).ToList<Node>();

                if (orderedNodes.Count >= 2)
                {
                    // Берем 2 первых элемента
                    List<Node> taken = orderedNodes.Take(2).ToList<Node>();

                    // Создадим родительский узел комбинацией частот
                    Node parent = new Node()
                    {
                        Symbol = '*',
                        Frequency = taken[0].Frequency + taken[1].Frequency,
                        Left = taken[0],
                        Right = taken[1]
                    };

                    nodes.Remove(taken[0]);
                    nodes.Remove(taken[1]);
                    nodes.Add(parent);
                }

                this.Root = nodes.FirstOrDefault();

            }

        }
Exemplo n.º 2
0
 public bool IsLeaf(Node node)
 {
     return (node.Left == null && node.Right == null);
 }