public static TreeNode GetParentNode(TreeNode node, int data) { if (node != null) { if (node.Data == data) { return(node); } if (node.Left != null && node.Left.Data == data) { return(node); } if (node.Right != null && node.Right.Data == data) { return(node); } var leftSubtree = TreeUtilities.GetParentNode(node.Left, data); var rightSubtree = TreeUtilities.GetParentNode(node.Right, data); return(leftSubtree ?? rightSubtree); } return(null); }
public void Delete(int data) { var parent = TreeUtilities.GetParentNode(this.Root, data); if (parent == null) { parent = this.Root; } if (parent != null) { bool isRoot; bool deleted = parent.DeleteLeaf(data, out isRoot); if (deleted && isRoot) { this.Root = null; } if (!deleted) { deleted = parent.DeleteWithOneChild(data); if (!deleted) { deleted = parent.DeleteWithTwoChildren(data); if (!deleted) { throw new InvalidOperationException( "Cannot remove node for value: " + data); } } } } }
public bool DeleteWithTwoChildren(int data) { bool isRoot; if (this.Data == data) { if (this.Left != null && this.Right != null) { int smallestChildValue = FindSmallestValue(this.Right); var smallestValueNodeToRemoveParent = TreeUtilities.GetParentNode(this.Right, smallestChildValue); bool isDeleted = smallestValueNodeToRemoveParent.DeleteLeaf(smallestChildValue, out isRoot); if (isDeleted && isRoot) { this.Right = null; } if (!isDeleted) { isDeleted = smallestValueNodeToRemoveParent.DeleteWithOneChild(smallestChildValue); if (!isDeleted) { return(false); } } this.Data = smallestChildValue; return(true); } } if (this.Left != null && this.Left.Data == data) { if (this.Left.Left != null && this.Left.Right != null) { int smallestChildValue = FindSmallestValue(this.Left.Right); var smallestValueNodeToRemoveParent = TreeUtilities.GetParentNode(this.Left, smallestChildValue); bool isDeleted = smallestValueNodeToRemoveParent.DeleteLeaf(smallestChildValue, out isRoot); if (isDeleted && isRoot) { this.Left = null; } if (!isDeleted) { isDeleted = smallestValueNodeToRemoveParent.DeleteWithOneChild(smallestChildValue); if (!isDeleted) { return(false); } } this.Left.Data = smallestChildValue; return(true); } } if (this.Right != null && this.Right.Data == data) { if (this.Right.Left != null && this.Right.Right != null) { int smallestChildValue = FindSmallestValue(this.Right.Right); var smallestValueNodeToRemoveParent = TreeUtilities.GetParentNode(this.Right, smallestChildValue); bool isDeleted = smallestValueNodeToRemoveParent.DeleteLeaf(smallestChildValue, out isRoot); if (!isDeleted) { isDeleted = smallestValueNodeToRemoveParent.DeleteWithOneChild(smallestChildValue); if (!isDeleted) { return(false); } } this.Right.Data = smallestChildValue; return(true); } } return(false); }