BST delete, successor and predecessor
لم يُترجم بعد؛ يُعرض باللغة الإنجليزية
عن هذا الدرس
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.
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]اقرأ الدرس خطوة بخطوة
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]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)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)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 childDelete 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, 80One 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, 80Two 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 childCopy 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)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, 80Cost: 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
أسئلة سريعة: 5
اختر إجابة واحدة لكل سؤال. يمكنك تغيير اختياراتك قبل التحقق منها.
01In the lesson's tree (50 at the root; 30 and 70; 20, 40, 60 and 80; 65 under 60), what is the successor of 60?
60 has a right subtree (just 65), so the successor is that subtree's smallest key: step right to 65 and go left as far as possible, which is nowhere. 65 is also the next key in the sorted row.
02In the same tree, what is the predecessor of 60?
60 has no left subtree, so climb until you arrive from a right child: 60 is 70's left child, so keep going; 70 is 50's right child, so stop. The predecessor is 50, the key just before 60 in sorted order.
03You delete a node that has exactly one child. What happens?
Every key in the child's subtree was already on the right side of the parent, so the child can simply take the deleted node's place. In the code, line 7 or line 8 returns the child, and the parent's link is set to it.
04Why does the successor of a node with two children never have a left child?
The search goes left until there is no left link, so the node it stops at has none. Deleting it is then case 1 (a leaf) or case 2 (one right child). It may still have a right child, like 60 with 65 under it.
05A tree was built by inserting 1, 2, 3, ..., 1000 in that order. Roughly how many nodes can delete visit?
Sorted inserts make a line: every node is the right child of the one before, so the height is n − 1 = 999. Delete costs O(h), so deleting 1000 walks past every node. A balanced tree of 1000 keys has height about log₂ 1000, which is close to 10.
المسرد
- Binary search tree (BST)
- A binary tree where every key in a node's left subtree is smaller than the node's key, and every key in its right subtree is bigger.
- In-order traversal
- Visit the left subtree, then the node, then the right subtree. In a BST this lists the keys in sorted order.
- Successor
- The node with the smallest key bigger than a given key: the next key in sorted order.
- Predecessor
- The node with the biggest key smaller than a given key: the key just before it in sorted order.
- Leaf
- A node with no children.
- Subtree
- A node together with everything below it.
- Height (h)
- The number of links on the longest path from the root down to a leaf.
- Hibbard deletion
- Deleting a node with two children by putting its successor in its place, proposed by T. Hibbard in 1962.
الملاحظات والمصادر
- Each node is drawn above its key's place in sorted order, so the row in front is the in-order traversal. When the root takes the key 60 it moves to 60's column; the tree's links are what really changed.
- CLRS and MIT 6.006 find a successor with parent links (right then far left, or climb). The Python here has no parent links: it walks down from the root and keeps the last node where it turned left, which is the same node.
- Using the predecessor in the two-children case works just as well (MIT 6.006 swaps with the predecessor when there is a left child). Always picking the successor, as Hibbard's 1962 method does, slowly skews a tree after many deletes.
- Copying the key is the short version. CLRS instead moves the successor node itself into place (transplant), which keeps node identities intact when other code holds references to them.
- Keys are assumed distinct, as in CLRS. With duplicates, insert here sends equal keys to the right.
- MIT 6.006 Introduction to Algorithms (Spring 2020), Lecture 6: Binary Trees, Part 1
- Sedgewick and Wayne, Algorithms 4th ed., §3.2 Binary Search Trees
- Cormen, Leiserson, Rivest and Stein, Introduction to Algorithms, 4th ed. (MIT Press, 2022), chapter 12
- Binary search tree: deletion, successor and predecessor (with CLRS page references)
- Python Tutorial: Classes
- Python Language Reference: Expressions (identity comparisons and Boolean operations)
اختبار يتاح بعد الخطوة الأخيرة.