private void getElements(IBSTNode currNode, BSTStack stack) { // add nodes into stack to use at getEnumerator() // null nodes not allowed if (currNode == null) { return; } if (currNode.isLeaf()) { // add element to stack stack.Push(currNode); } else { // unbox BSTInternalNode node = (BSTInternalNode)currNode; // get left node this.getElements(node.Left, stack); // add current element to stack stack.Push(node); // get right nodes this.getElements(node.Right, stack); } }
/// <summary> /// Provides implementation so that the items of the list can be accessed by /// foreach loop iterations. /// </summary> /// <returns>A KeyValuePair<int, string> object.</returns> public IEnumerator <KeyValuePair <int, string> > GetEnumerator() { // create a new stack of nodes BSTStack stack = new BSTStack(); // populate stack, start from root this.getElements(this._root, stack); // return values from top element then pop it out while (!stack.isEmpty()) { yield return(new KeyValuePair <int, string>(stack.Top.Key, stack.Top.Value)); stack.Pop(); } }