ENع
→BST delete
الدرس 15 · Search trees

BST delete, successor and predecessor

لم يُترجم بعد؛ يُعرض باللغة الإنجليزية

14 دقيقة10 خطوات5 أسئلةIntermediate
عن هذا الدرس

Searching and inserting into a binary search tree only ever adds a leaf. Deleting is harder: the node may sit in the middle with links on both sides. This lesson finds a key's successor and predecessor (the keys just after and just before it in sorted order), then uses the successor to delete any node while keeping the tree sorted. The Software lesson "Trees" covers search, insert and the in-order walk, and "Tree traversals: pre-order, in-order, post-order and level order" shows why in-order reads the keys in sorted order.

ستتعلّم

حدّد ما تشعر بأنك أتقنته. هذا التقييم الذاتي لا يؤثر في درجة الدرس.

شكل 15 · تفاعلي
01 / 10

A sorted tree

This binary search tree holds 8 keys. Every key in a node's left subtree is smaller, every key in its right subtree is bigger. Each node stands above its place in sorted order, so the row in front reads 20 to 80.

insert order: 50, 30, 70, 20, 40, 60, 80, 65
in-order:     20, 30, 40, 50, 60, 65, 70, 80
height:       3 (longest root-to-leaf path, in links)

the program this figure runs (python3, as-is):
class Node:
    def __init__(self, key):
        self.key = key
        self.left = None
        self.right = None

def insert(t, k):
    if t is None: return Node(k)
    if k < t.key: t.left = insert(t.left, k)
    else: t.right = insert(t.right, k)
    return t

def delete(t, k):
    if t is None: return t
    if k < t.key:
        t.left = delete(t.left, k)
    elif k > t.key:
        t.right = delete(t.right, k)
    elif t.left is None: return t.right
    elif t.right is None: return t.left
    else:
        s = t.right
        while s.left: s = s.left
        t.key = s.key
        t.right = delete(t.right, s.key)
    return t

def successor(t, k):      # smallest key bigger than k
    s = None
    while t:
        if k < t.key: s, t = t, t.left
        else: t = t.right
    return s

def predecessor(t, k):    # biggest key smaller than k
    p = None
    while t:
        if k > t.key: p, t = t, t.right
        else: t = t.left
    return p

def inorder(t):
    return inorder(t.left) + [t.key] + inorder(t.right) if t else []

root = None
for k in [50, 30, 70, 20, 40, 60, 80, 65]:
    root = insert(root, k)
print(inorder(root))
print(successor(root, 50).key, successor(root, 40).key, predecessor(root, 50).key)
for k in [20, 30, 50]:
    root = delete(root, k)
    print(inorder(root))

prints:
[20, 30, 40, 50, 60, 65, 70, 80]
60 50 40
[30, 40, 50, 60, 65, 70, 80]
[40, 50, 60, 65, 70, 80]
[40, 60, 65, 70, 80]
جارٍ تحميل الرسم…
أو ← →
اقرأ الدرس خطوة بخطوة
  1. A sorted tree

    This binary search tree holds 8 keys. Every key in a node's left subtree is smaller, every key in its right subtree is bigger. Each node stands above its place in sorted order, so the row in front reads 20 to 80.

    insert order: 50, 30, 70, 20, 40, 60, 80, 65
    in-order:     20, 30, 40, 50, 60, 65, 70, 80
    height:       3 (longest root-to-leaf path, in links)
    
    the program this figure runs (python3, as-is):
    class Node:
        def __init__(self, key):
            self.key = key
            self.left = None
            self.right = None
    
    def insert(t, k):
        if t is None: return Node(k)
        if k < t.key: t.left = insert(t.left, k)
        else: t.right = insert(t.right, k)
        return t
    
    def delete(t, k):
        if t is None: return t
        if k < t.key:
            t.left = delete(t.left, k)
        elif k > t.key:
            t.right = delete(t.right, k)
        elif t.left is None: return t.right
        elif t.right is None: return t.left
        else:
            s = t.right
            while s.left: s = s.left
            t.key = s.key
            t.right = delete(t.right, s.key)
        return t
    
    def successor(t, k):      # smallest key bigger than k
        s = None
        while t:
            if k < t.key: s, t = t, t.left
            else: t = t.right
        return s
    
    def predecessor(t, k):    # biggest key smaller than k
        p = None
        while t:
            if k > t.key: p, t = t, t.right
            else: t = t.left
        return p
    
    def inorder(t):
        return inorder(t.left) + [t.key] + inorder(t.right) if t else []
    
    root = None
    for k in [50, 30, 70, 20, 40, 60, 80, 65]:
        root = insert(root, k)
    print(inorder(root))
    print(successor(root, 50).key, successor(root, 40).key, predecessor(root, 50).key)
    for k in [20, 30, 50]:
        root = delete(root, k)
        print(inorder(root))
    
    prints:
    [20, 30, 40, 50, 60, 65, 70, 80]
    60 50 40
    [30, 40, 50, 60, 65, 70, 80]
    [40, 50, 60, 65, 70, 80]
    [40, 60, 65, 70, 80]
  2. Successor: right, then left

    The successor of a key is the next one in sorted order. 50 has a right subtree, so the answer is in there: its smallest key. Step right to 70, then go left until you can't: 60.

    successor(50): 50 has a right child
      walk: 50 → 70 → 60
      first step right, then left while there is a left child
      answer: 60 (next in the row after 50)
  3. No right subtree: climb

    40 has no right subtree, so its successor is above it. Climb while you come up from a right child: 40 hangs right of 30. Then 30 hangs left of 50, so stop there: 50 is next.

    successor(40): 40 has no right child
      climb: 40 → 30 → 50
      40 is 30's right child: keep climbing
      30 is 50's left child: stop, the answer is 50
      answer: 50
    
    without parent links: walk down from the root and keep
    the last node where you turned left (the Python version)
  4. Predecessor: the mirror image

    The predecessor is the key just before, so swap left and right. 50 has a left subtree: step left to 30, then go right until you can't: 40. With no left subtree you would climb instead.

    predecessor(50): 50 has a left child
      walk: 50 → 30 → 40
      first step left, then right while there is a right child
      answer: 40 (the cell before 50 in the row)
    no left child: climb until you come up from a right child
  5. Delete a leaf: 20

    To delete 20, search for it: left at 50, left at 30. Node 20 has no children, so line 7 returns its right link, which is None. 30's left link becomes None and the leaf just drops off.

    delete(root, 20)
      50: 20 < 50, line 4: go left
      30: 20 < 30, line 4: go left
      20: found; left is None, line 7: return t.right (None)
      30.left = None
    in-order: 30, 40, 50, 60, 65, 70, 80
  6. One child: lift it up

    Now delete 30. It has one child, 40, on its right. Line 7 returns that child, so 50's left link points straight at 40, which rises into 30's place. 40 is still smaller than 50: the order holds.

    delete(root, 30)
      50: 30 < 50, line 4: go left
      30: found; left is None, line 7: return t.right (node 40)
      50.left = node 40
    (a node with only a left child takes line 8 the same way)
    in-order: 40, 50, 60, 65, 70, 80
  7. Two children: find the successor

    Delete 50, the root. It has two children, but only one node can take its place. Lines 10 and 11 pick its successor: right to 70, then left as far as possible: 60. It has no left child.

    delete(root, 50): found at the root, both links are set
      line 10: s = t.right (70)
      line 11: while s.left: s = s.left (60; 60.left is None)
      the successor is the smallest key in the right subtree,
      so it can never have a left child
  8. Copy the successor's key

    Line 12 copies 60 into the root. Everything on the left is still smaller than 60, and everything on the right is at least 60, so the order holds. For a moment 60 is in the tree twice.

    line 12: t.key = s.key
      the root now holds 60
      left subtree:  40 (all < 60)
      right subtree: 60, 65, 70, 80 (60 still there)
  9. Delete the old successor

    Line 13 deletes 60 from the right subtree. That old node has no left child, so line 7 returns its right child: 65 rises under 70. The row now reads 40, 60, 65, 70, 80: still sorted.

    line 13: t.right = delete(t.right, 60)
      70: 60 < 70, go left
      60: found; left is None, line 7: return t.right (node 65)
      70.left = node 65
    in-order: 40, 60, 65, 70, 80
    preorder: 60, 40, 70, 65, 80
  10. Cost: one path, O(h)

    Each operation here walked one path, down or up, so it costs O(h), where h is the tree's height: now 2. A balanced tree keeps h near log₂ n; one built from sorted keys is a line, with h = n − 1.

    search, successor, predecessor, insert, delete: O(h)
    this tree: n = 5, h = 2
    longest path: 60 → 70 → 65
    balanced: h about log₂ n   ·   sorted inserts: h = n − 1

اختبار يتاح بعد الخطوة الأخيرة.