The.Algorithm.Design.Manual.Springer-Verlag.1998

The.Algorithm.Design.Manual.Springer-Verlag.1998 The.Algorithm.Design.Manual.Springer-Verlag.1998

18.04.2013 Views

Lecture 8 - binary trees Tree-insert(T,z) left[x] right[x] y = NIL x = root[T] while if y = NIL do y = x then y is maintained as the parent of x, since x eventually becomes NIL. else if key[z] < key[y] The final test establishes whether the NIL was a left or right turn from y. Insertion takes time proportional to the height of the tree, O(h). file:///E|/LEC/LECTUR17/NODE8.HTM (7 of 13) [19/1/2003 1:34:46] if key[z] < key[x] then else then x = else x =

Lecture 8 - binary trees Listen To Part 8-12 Tree Deletion Deletion is somewhat more tricky than insertion, because the node to die may not be a leaf, and thus effect other nodes. Case (a), where the node is a leaf, is simple - just NIL out the parents child pointer. Case (b), where a node has one chld, the doomed node can just be cut out. Case (c), relabel the node as its successor (which has at most one child when z has two children!) and delete the successor! This implementation of deletion assumes parent pointers to make the code nicer, but if you had to save space they could be dispensed with by keeping the pointers on the search path stored in a stack. Tree-Delete(T,z) if (left[z] = NIL) or (right[z] = NIL) if if if p[y] = NIL then else Tree-Successor(z) then else then then file:///E|/LEC/LECTUR17/NODE8.HTM (8 of 13) [19/1/2003 1:34:46] else if (y = left[p[y]])

Lecture 8 - binary trees<br />

Listen To Part 8-12<br />

Tree Deletion<br />

Deletion is somewhat more tricky than insertion, because the node to die may not be a leaf, and thus effect other nodes.<br />

Case (a), where the node is a leaf, is simple - just NIL out the parents child pointer.<br />

Case (b), where a node has one chld, the doomed node can just be cut out.<br />

Case (c), relabel the node as its successor (which has at most one child when z has two children!) and delete the successor!<br />

This implementation of deletion assumes parent pointers to make the code nicer, but if you had to save space they could be<br />

dispensed with by keeping the pointers on the search path stored in a stack.<br />

Tree-Delete(T,z)<br />

if (left[z] = NIL) or (right[z] = NIL)<br />

if<br />

if<br />

if p[y] = NIL<br />

then<br />

else Tree-Successor(z)<br />

then<br />

else<br />

then<br />

then<br />

file:///E|/LEC/LECTUR17/NODE8.HTM (8 of 13) [19/1/2003 1:34:46]<br />

else if (y = left[p[y]])

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

Saved successfully!

Ooh no, something went wrong!