Exemplo n.º 1
0
        private IEnumerable <TernaryNode <TValue> > Traversal(TernaryNode <TValue> parent)
        {
            var stack = new Stack <TernaryNode <TValue> >();

            stack.Push(parent);

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

                if (node.Left != null)
                {
                    stack.Push(node.Left);
                }

                if (node.Middle != null)
                {
                    stack.Push(node.Middle);
                }

                if (node.Right != null)
                {
                    stack.Push(node.Right);
                }

                if (node.IsLeaf)
                {
                    yield return(node);
                }
            }
        }
Exemplo n.º 2
0
        private void Insert(String partOfKey, TValue value, bool update)
        {
            var index  = 0;
            var length = partOfKey.Length - 1;

            if (_root == null)
            {
                _root = new TernaryNode <TValue> {
                    Char = partOfKey[0]
                }
            }
            ;

            var node = _root;

            while (true)
            {
                var @char = partOfKey[index];
                if (@char < node.Char)
                {
                    if (node.Left == null)
                    {
                        node.Left = new TernaryNode <TValue> {
                            Char = @char
                        }
                    }
                    ;

                    node = node.Left;
                }
                else if (@char > node.Char)
                {
                    if (node.Right == null)
                    {
                        node.Right = new TernaryNode <TValue> {
                            Char = @char
                        }
                    }
                    ;

                    node = node.Right;
                }
                else if (index < length)
                {
                    if (node.Middle == null)
                    {
                        node.Middle = new TernaryNode <TValue> {
                            Char = partOfKey[index + 1]
                        }
                    }
                    ;

                    node = node.Middle;
                    index++;
                }
                else
                {
                    if (!node.IsLeaf)
                    {
                        node.IsLeaf = true;
                        node.Key    = partOfKey;
                        node.Value  = value;

                        return;
                    }

                    if (update)
                    {
                        node.Key   = partOfKey;
                        node.Value = value;

                        return;
                    }

                    throw new Exception("Key already exists");
                }
            }
        }