问题
I have a trouble understanding what's a successor of a node X
whenever it doesn't have a right child.
From what I had understood, if a node X
had no right child, then it would not have a successor.
But my textbook says the following:
If the right sub-tree of node
X
is empty andX
has a successorY
...
How can X
have a successor when it has not right child?
回答1:
The successor is simply the next element in the ordered sequence; it doesn't necessarily have to be a child element.
For example, the successor of 5
below is 7
:
7
/ \
5 8
回答2:
The successor of a node X
is the smallest greater element S
in the tree with respect to X
. That is, for all nodes in the set G = { Si | Si > X }
, then S
is an element of G
and S <= Si
, for i=1..n
.
In a BST, for any node X
, all elements in left subtree of X
are smaller than X
, while all elements in its right subtree are greater than it.
Scenarios
Now consider X
as an arbitrary node in your tree, and let P
be its parent node. In both of the following cases it does not matter if X
has or not a left subtree, which contains elements that are smaller than X
.
X
has a right subtreeThe successor of
X
by definition lies in right subtree. The smallest element of the right subtree is the leftmost element, which is the successor ofX
. If the right subtree contains only one node then that is the successor ofX
.X
has no right subtreeX
is the left child of its parentP
Then parent
P
is the successor.X
is a right child of its parentP
Then the first ancestor of
X
, lets call itA
, such thatX
falls in the left subtree ofA
is the successor ofX
.
Example
10
/ \
5 14
/ \ / \
3 7 11 15
/ \ /
1 4 6
Examples for case 1
- Successor of 3 is 4 (or, similarly, the successor of 14 is 15)
- Successor of 10 is 11 (or, similarly, the successor of 5 is 6)
Examples for case 2
- Successor of 7 is 10 (or, similarly, the successor of 4 is 5)
- Successor of 11 is 14 (or, similarly, the successor of 6 is 7)
来源:https://stackoverflow.com/questions/21512227/how-can-a-node-x-without-right-child-have-a-successor