public bool Remove(T value) { p = -1; ANode <T> node = _root; while (node.IsNotNull()) { path[++p] = node; if (value.CompareTo(node.Item) == 0) { RemoveNode(node); return(true); } if (value.CompareTo(node.Item) < 0) { node = node.Left; } else { node = node.Right; } } return(false); }
private void Print(ANode <T> root) { if (root.IsNotNull()) { Print(root.Left); Console.Write(root.Item + " "); Print(root.Right); } }
public bool Add(T value) { if (IsEmpty) { // here just create the root node. _root = new ANode <T>(value); _root.BalanceFactor = 0; return(true); } p = 0; ANode <T> current = _root, prev = null; while (current.IsNotNull()) { path[p++] = current; if (current.Item.CompareTo(value) == 0) { // item exists. return(false); } prev = current; current = (value.CompareTo(current.Item) < 0) ? current.Left : current.Right; } // current = new ANode <T>(value); current.BalanceFactor = 0; if (value.CompareTo(prev.Item) < 0) { prev.Left = current; } else { prev.Right = current; } path[p] = current; int bf = 0; while (p > 0) { // compare to node's parent. bf = (value.CompareTo(path[p - 1].Item) < 0) ? 1 : -1; path[--p].BalanceFactor += bf; // change bf of parent node. bf = path[p].BalanceFactor; if (bf == 0) { // here means the tree is balanced. return(true); } else if (Math.Abs(bf) == 2) { // Balance mimimum unbalanced tree. RotateSubTree(bf); return(true); } } return(true); }