System.util.collections.OrderedTreeEnumerator.NextElement C# (CSharp) Method

NextElement() public method

NextElement
public NextElement ( ) : object
return object
        public object NextElement()
        {
            if(stack.Count == 0)

                throw new InvalidOperationException("Element not found");

            // the top of stack will always have the next item
            // get top of stack but don't remove it as the next nodes in sequence
            // may be pushed onto the top
            // the stack will be popped after all the nodes have been returned
            OrderedTreeNode node = (OrderedTreeNode) stack.Peek(); //next node in sequence

            if(ascending) {
                if(node.Right == sentinelNode) {
                    // yes, top node is lowest node in subtree - pop node off stack
                    OrderedTreeNode tn = (OrderedTreeNode) stack.Pop();
                    // peek at right node's parent
                    // get rid of it if it has already been used
                    while(HasMoreElements()&& ((OrderedTreeNode) stack.Peek()).Right == tn)
                        tn = (OrderedTreeNode) stack.Pop();
                }
                else {
                    // find the next items in the sequence
                    // traverse to left; find lowest and push onto stack
                    OrderedTreeNode tn = node.Right;
                    while(tn != sentinelNode) {
                        stack.Push(tn);
                        tn = tn.Left;
                    }
                }
            }
            else { // descending, same comments as above apply
                if(node.Left == sentinelNode) {
                    // walk the tree
                    OrderedTreeNode tn = (OrderedTreeNode) stack.Pop();
                    while(HasMoreElements() && ((OrderedTreeNode)stack.Peek()).Left == tn)
                        tn = (OrderedTreeNode) stack.Pop();
                }
                else {
                    // determine next node in sequence
                    // traverse to left subtree and find greatest node - push onto stack
                    OrderedTreeNode tn = node.Left;
                    while(tn != sentinelNode) {
                        stack.Push(tn);
                        tn = tn.Right;
                    }
                }
            }

            // the following is for .NET compatibility (see MoveNext())
            Key = node.Key;
            Value = node.Data;
            // ******** testing only ********

            return keys == true ? node.Key : node.Data;
        }