protected void Copy(StdNode <Key, Value> src, StdNode <Key, Value> dst) { dst.NodeKey = src.NodeKey; dst.NodeValue = src.NodeValue; dst.Left = src.Left; dst.Right = src.Right; }
/// <summary> /// Помещение данных в дерево под ключом /// </summary> public void Insert(Key key, Value value) { if (NodeKey.CompareTo(default(Key)) == 0) { NodeKey = key; NodeValue = value; } else if (NodeKey.CompareTo(key) == 0) { NodeValue = value; } else if (NodeKey.CompareTo(key) > 0) { if (Left == null) { Left = new StdNode <Key, Value>(key, value); } else { Left.Insert(key, value); } } else if (NodeKey.CompareTo(key) < 0) { if (Right == null) { Right = new StdNode <Key, Value>(key, value); } else { Right.Insert(key, value); } } }
/// <summary> /// Удаление данных из дерева по ключу /// </summary> public void Delete(Key key) { if (NodeKey.CompareTo(key) == 0) { if (Left == null && Right == null) { NodeKey = default(Key); } else if (Left == null) { Copy(Right, this); } else if (Right == null) { Copy(Left, this); } else { if (Right.Left == null) { NodeKey = Right.NodeKey; NodeValue = Right.NodeValue; Right = Right.Right; } else { var parent = Right; var node = parent.Left; while (node.Left != null) { parent = node; node = parent.Left; } NodeKey = node.NodeKey; NodeValue = node.NodeValue; if (node.Right == null) { parent.Left = null; } else { parent.Left = node.Right; } } } } else if (NodeKey.CompareTo(key) > 0 && Left != null) { Left.Delete(key); if (Left.NodeKey.CompareTo(default(Key)) == 0) { Left = null; } } else if (NodeKey.CompareTo(key) < 0 && Right != null) { Right.Delete(key); if (Right.NodeKey.CompareTo(default(Key)) == 0) { Right = null; } } }