private void AddToParent(BinaryTreeNode <T> node, BinaryTreeNode <T> parent) { if (node.CompareTo(parent) > 0) { // node is bigger or equal to parent if (parent.Right == null) { parent.Right = node; } else { AddToParent(node, parent.Right); } } else { // node is smaller than parent if (parent.Left == null) { parent.Left = node; } else { AddToParent(node, parent.Left); } } }
/// <summary> /// Finds and returns the first node containing the specified value. If the value /// is not found, returns null. Also returns the parent of the found node (or null) /// which is used in Remove. /// </summary> /// <param name="value">The value to search for</param> /// <param name="parent">The parent of the found node (or null)</param> /// <returns>The found node (or null)</returns> private BinaryTreeNode <T> FindWithParent(T value, out BinaryTreeNode <T> parent) { // Now, try to find data in the tree BinaryTreeNode <T> current = _head; parent = null; // while we don't have a match while (current != null) { int result = current.CompareTo(value); if (result > 0) { // if the value is less than current, go left. parent = current; current = current.Left; } else if (result < 0) { // if the value is more than current, go right. parent = current; current = current.Right; } else { // we have a match! break; } } return(current); }
private BinaryTreeNode FindByValue(int value, BinaryTreeNode headOfSubtree = null) { BinaryTreeNode current = headOfSubtree ?? _head; while (current != null) { int result = current.CompareTo(value); if (result > 0) { current = current.LeftNode; } else if (result < 0) { current = current.RightNode; } else { break; } } return(current); }