BST Operations: Pseudocode (Part 3)
Learn to perform operations on binary search trees.
We'll cover the following...
The getSuccessor
function
Another property of a binary search tree is that we can easily find the successor of a node. The successor of node A
is node B
, with the closest bigger value than node A
. In other words, B
> A
and there is no other node C
where C
> A
and C
< B
.
For example, finding the successor (or predecessor) value is useful to efficiently find the colleague with the closest age (or height, income, and so on) to ours.
Let’s consider the following BST and try to find the successor node for some of the nodes inside the tree.
- The successor of node
1
is node2
because2
is the first value bigger than1
. - The successor of node
2
is node4
because4
is the first value bigger than2
. Note that a successor is not the next consecutive value but the first bigger value. - The successor of node
14
is15
because15
is the first value bigger than14
. - The successor of node
7
is8
because8
is the first value bigger than7
. - Node
16
doesn’t have a successor because it’s the biggest value inside the tree. In other words, the rightmost node in a BST does not have a successor because it’s the biggest node.
Spend time analyzing the tree and ensuring you understand the concept of a successor node.
Let’s try to find an algorithm for determining the successor node.
We’ll look at some of the nodes to try to find an algorithm:
- If we look at node
2
, its successor is node4
, which is its right child. - If we look at node
7
, its successor is node8
, which is inside the right subtree of7
, but it is not the immediate right child (which would be15
). - From these two observations, we can say that the successor of node
A
is somewhere inside the right subtree ofA
. But, if we also recall that the right subtree contains only values bigger than the value ofA
, we can deduce that the successor of nodeA
is the minimum value in the right subtree. It makes sense since the successor is the first bigger value than nodeA
.- The minimum value in the right subtree of
2
is4
. Therefore4
is the successor of2
. - The minimum value in the right subtree of
7
is8
. Therefore8
is the successor of7
. - Recall that to find the minimum value in a tree (or subtree), we find the leftmost node in that tree (or subtree). For example,
8
is the leftmost node in the right subtree of7
.
- The minimum value in the right subtree of
See the following ...