Пример #1
0
        // in order traversal, returns a string containing all elements
        // implemented making use of the parent nodes to test their functionality
        public string ParentTraverse()
        {
            BinarySearchTreeNode <T> current = root;
            BinarySearchTreeNode <T> previous;
            string output = "";

            if (current == null)
            {
                return(output);
            }
            // loops until returning to root from the right or from left if there is no right branch
            do
            {
                // moves to furthest left child of current and adds its value to output, sets previous to current
                while (current.left != null)
                {
                    current = current.left;
                }
                previous = current;
                output  += current.value + " ";

                // traverses parent nodes until reaching a node with an unvisited right node or reaching the root
                while ((current.right == null || current.right == previous) && current.parent != null)
                {
                    // sets previous to current then sets current to parent and adds value to output if previous was not on right side
                    previous = current;
                    current  = current.parent;
                    if (current.right != previous)
                    {
                        output += current.value + " ";
                    }
                }
                // if there is an unvisited branch to the right, moves current to right
                if (current.right != previous && current.right != null)
                {
                    current = current.right;
                }
            } while (current.parent != null);
            return(output);
        }
Пример #2
0
 //private insert, takes a node and item and attempts to insert at that node
 // if node is not empty recurses on left/right node if item is smaller/larger than item at current position
 private BinarySearchTreeNode <T> Insert(BinarySearchTreeNode <T> child, T item)
 {
     if (child == null)
     {
         child       = new BinarySearchTreeNode <T>();
         child.value = item;
     }
     // insertion logic, if the value (v )is < root, insert to the root.left
     // otherwise it's >=, so insert to the right
     // connects node to parent after
     else if (item.CompareTo(child.value) < 0)
     {
         child.left        = Insert(child.left, item);
         child.left.parent = child;
     }
     else
     {
         child.right        = Insert(child.right, item);
         child.right.parent = child;
     }
     return(child);
 }