Binary search tree: remove node: Difference between revisions

From Algowiki
Jump to navigation Jump to search
Line 43: Line 43:


'''Implementation:'''
'''Implementation:'''
# If <math>p'.right.right = void</math>:
# If <math>p'</math>.right.right = void:
## Set <math>p.key := p'.right.key</math>.
## Set <math>p</math>.key := <math>p'</math>.right.key.
## Set <math>p'.right := p'.right.left</math>.
## Set <math>p'</math>.right := <math>p'</math>.right.left.
# Terminate the algorithm.
# Terminate the algorithm.



Revision as of 14:20, 18 May 2015

General Information

Algorithmic problem: See the remark clause of Binary Search Tree; pointer [math]\displaystyle{ p }[/math] as defined there is the input.

Prerequisites: [math]\displaystyle{ p }[/math].left [math]\displaystyle{ \neq }[/math] void.

Type of algorithm: loop

Auxiliary data: A pointer [math]\displaystyle{ p' }[/math] of type "pointer to a binary search tree node of type [math]\displaystyle{ \mathcal{K} }[/math]."

Abstract View

Invariant:

  1. The immediate predecessor of K is in the range of [math]\displaystyle{ p' }[/math].
  2. It is [math]\displaystyle{ p' }[/math].right = void.

Variant: The pointer [math]\displaystyle{ p' }[/math] descends one level deeper, namely to [math]\displaystyle{ p }[/math]'.right.

Break condition: It is [math]\displaystyle{ p' }[/math].right.right = void.

Induction Basis

Abstract view: If [math]\displaystyle{ p.left }[/math] is the immediate predecessor of K, overwrite K by its immediate predecessor and terminate; otherwise, initialize [math]\displaystyle{ p' }[/math].

Implementation:

  1. If [math]\displaystyle{ p }[/math].left.right = void:
    1. Set [math]\displaystyle{ p }[/math].key := p.left.key.
    2. Set [math]\displaystyle{ p }[/math].left := p.left.left.
    3. Terminate the algorithm.
  2. Otherwise, set [math]\displaystyle{ p' }[/math] := p.left.

Proof: Obvious.

Induction Step

Abstract view: If [math]\displaystyle{ p'.right }[/math] is the immediate predecessor of K, overwrite K by its immediate predecessor and terminate; otherwise, let p' descend one level deeper.

Implementation:

  1. If [math]\displaystyle{ p' }[/math].right.right = void:
    1. Set [math]\displaystyle{ p }[/math].key := [math]\displaystyle{ p' }[/math].right.key.
    2. Set [math]\displaystyle{ p' }[/math].right := [math]\displaystyle{ p' }[/math].right.left.
  2. Terminate the algorithm.

Correctness: Obvoius.

Complexity

Statement: The complexity is in [math]\displaystyle{ \mathcal{O}(T\cdot h)\subseteq\mathcal{O}(T\cdot n) }[/math] in the worst case, where [math]\displaystyle{ n }[/math] is the length of the sequence, [math]\displaystyle{ h }[/math] the height of the tree, and [math]\displaystyle{ T }[/math] the complexity of the comparison.

Proof: Obvious.