25.07.2017 Views

Intro-CSharp-Book-v2015

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Глава 17. Дървета и графи 715<br />

}<br />

node = replacement;<br />

// Case 1 and 2: If the node has at most one child<br />

BinaryTreeNode theChild = node.leftChild != null ?<br />

node.leftChild : node.rightChild;<br />

// If the element to be deleted has one child<br />

if (theChild != null)<br />

{<br />

theChild.parent = node.parent;<br />

// Handle the case when the element is the root<br />

if (node.parent == null)<br />

{<br />

root = theChild;<br />

}<br />

else<br />

{<br />

// Replace the element with its child subtree<br />

if (node.parent.leftChild == node)<br />

{<br />

node.parent.leftChild = theChild;<br />

}<br />

else<br />

{<br />

node.parent.rightChild = theChild;<br />

}<br />

}<br />

}<br />

else<br />

{<br />

// Handle the case when the element is the root<br />

if (node.parent == null)<br />

{<br />

root = null;<br />

}<br />

else<br />

{<br />

// Remove the element - it is a leaf<br />

if (node.parent.leftChild == node)<br />

{<br />

node.parent.leftChild = null;<br />

}<br />

else<br />

{<br />

node.parent.rightChild = null;<br />

}<br />

}

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!