/// <summary> /// Creates a clone of the current instance of the tree node. /// </summary> /// <returns>A cloned instance of the tree node.</returns> public object Clone() { BinaryTreeNode clone = new BinaryTreeNode(); if (_value is ICloneable) clone.Value = (IComparable) ((ICloneable) _value).Clone(); else clone.Value = _value; if (LeftChild != null) clone.LeftChild = LeftChild.Clone() as BinaryTreeNode; if (RightChild != null) clone.RightChild = RightChild.Clone() as BinaryTreeNode; return clone; }
/// <summary> /// Adds new content to the binary search tree. /// </summary> /// <param name="data"></param> public virtual void Add(IComparable data) { // first, create a new Node BinaryTreeNode n = new BinaryTreeNode(data); int result; // now, insert n into the tree // trace down the tree until we hit a NULL IBinaryTreeNode current = _root, parent = null; // define variable for comparisons IComparable comparableval = null; while (current != null) { comparableval = current.Value as IComparable; if (comparableval == null) return; // unable to perform insert - do nothing result = comparableval.CompareTo(n.Value); if (result == 0) // they are equal - inserting a duplicate - do nothing return; else if (result > 0) { // current.Value > n.Value // therefore, n must be added to current's left subtree parent = current; current = current.LeftChild; } else if (result < 0) { // current.Value < n.Value // therefore, n must be added to current's right subtree parent = current; current = current.RightChild; } } // ok, at this point we have reached the end of the tree _count++; if (parent == null) // the tree was empty _root = n; else { // store a reference to the parent n.Parent = parent; comparableval = parent.Value as IComparable; if (comparableval != null) { result = comparableval.CompareTo(n.Value); if (result > 0) // parent.Value > n.Value // therefore, n must be added to parent's left subtree parent.LeftChild = n; else if (result < 0) // parent.Value < n.Value // therefore, n must be added to parent's right subtree parent.RightChild = n; } } }