To get the successor inorder of this node N, we use the following rules:
- If it
Nhas the correct child R, then
inorderSuccessor(N)the left-most decedent R. - Else
inorderSuccessor(N)is closest ancestor M, N(if it exists) such that Noriginates from a left child device M. If there is no such ancestor, inorderSucessor does not exist.
Consider the sample tree:
A
/ \
B C
/ \
D E
/
F
Whose bypass gives in order: D B F E A C
inorderSuccessor(A)= C, C - A.
inorderSuccessor(B)= F F - B.
inorderSuccessor(C)= .
inorderSuccessor(D)= B B D.
inorderSuccessor(E)= A. E , 2. E, B, E B, B A B A, A .
inorderSuccessor(F)= E F E.
:
treeNodePtr inorderSucessor(treeNodePtr N) {
if(N) {
treeNodePtr tmp;
if(N->right) {
tmp = N->right;
while(tmp->left) {
tmp = tmp->left;
}
} else {
while((tmp = N->parent)) {
if(tmp->left == N) {
break;
}
N = tmp;
}
}
return tmp;
}
return NULL;
}