public void Remove(int key) { if (_root == null) { Console.WriteLine("Tree is empty!"); return; } if (_root.Search(key) == null) { Console.WriteLine("No node with this key!"); return; } _root.Remove(key); }
public void Remove(int key) { if (key < _key) { _leftChild?.Remove(key); return; } if (key > _key) { _rightChild?.Remove(key); return; } bool isThisALeftChild = this == _parent.GetChild(true); // No children case if (GetChild(true) == null && GetChild(false) == null) { if (isThisALeftChild) { _parent.SetChild(null, true); } else { _parent.SetChild(null, false); } return; } // One child case if (GetChild(true) == null || GetChild(false) == null) { if (GetChild(true) != null) { _parent.SetChild(GetChild(true), isThisALeftChild); GetChild(true).SetParent(_parent); return; } if (GetChild(false) != null) { _parent.SetChild(GetChild(false), isThisALeftChild); GetChild(false).SetParent(_parent); return; } } // Both children case // Finding the successor BinaryTreeNode successorNode = _rightChild; while (successorNode.GetChild(true) != null) { successorNode = successorNode.GetChild(true); } CopyFrom(successorNode); // If the successor has no children if (successorNode.GetChild(true) == null && successorNode.GetChild(false) == null) { if (successorNode == _rightChild) { SetChild(null, false); } else { successorNode.GetParent().SetChild(null, true); } return; } // The successor has a right child if (successorNode == _rightChild) { SetChild(successorNode.GetChild(false), false); } else { successorNode.GetParent().SetChild(successorNode.GetChild(false), true); successorNode.GetChild(false).SetParent(successorNode.GetParent()); } }