liveBook · Manning

Predecessor

As explained in Grokking Data Structures

An in-order predecessor is the greatest node value that precedes a specified node value in the sorted order of a binary search tree.

Imagine lining up a collection of distinct values from smallest to largest. The predecessor of a value is the one immediately before it. In a binary search tree (BST), that value may not be stored in an adjacent node, so finding it means following the tree’s links. section 11.14

To find a node’s predecessor in the whole BST:

  • If the node has a left subtree, find the maximum value in that subtree. section 11.14
  • Otherwise, if the node is a right child, its parent is the predecessor. section 11.14
  • Otherwise, climb toward the root until you reach a node that is a right child. Its parent is the predecessor. If you reach the root without finding one, there is no predecessor: the starting node is the tree’s minimum. section 11.14

Replacing a node during deletion

Suppose the node containing 4 has two children, and the maximum value in its left subtree is 3. Replace 4 with its predecessor, 3, then delete the original node containing 3. That node cannot have a right subtree—otherwise 3 would not have been the left subtree’s maximum—so its removal is a simpler deletion case. section 11.11

A sorted array or sorted doubly linked list puts a present predecessor immediately before its value. A BST instead takes O(h) time to find one, where h is the tree’s height; in a balanced BST, that is O(log(n)). The parent-climbing description assumes access to parent links. Without them, implementation requires backtracking, which is left for further study. section 11.14 section 11.20

How Grokking Data Structures covers it

How deep it goes
Defines the predecessor and walks through tree cases and deletion, but defers implementation without parent links.
Examples
Uses deletion of value 4 with predecessor 3 and contrasts BST navigation with adjacent elements in sorted arrays and doubly linked lists.
What it assumes
Assumes familiarity with BST nodes, subtrees, and child links while defining predecessor from sorted order.
What you can do after
Practice/perform it: identify a BST node’s predecessor from its left subtree or ancestors and use it in two-child deletion.
How it connects
Connects predecessor to successor, subtree maximum, binary search tree deletion, and balanced binary search trees.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Grokking Data Structures. The section links point to the parts of the book it draws on.