Precursor and successor
This article describes the predecessor and successor of the binary tree. For more information about the concept of the Binary Tree, see my blog ***
Given a node in a binary search tree, it is sometimes required to find its successor in the central order traversal order. If all the keywords are different, then the successor of a knot of X is the smallest of all the nodes whose (node value) is greater than X.
There are two scenarios:
Scenario 1: If the right subtree of node X is not empty, the successor of node X is the leftmost node in the right subtree.
Case 2: The right subtree of node X is empty, and the successor of node X is Y. Then Y is the lowest ancestor node of X, and the left son of Y is also the ancestor of x (x itself can also be seen as the ancestor of X)
1 BT* TreeSuccessor(BT* T) 2 { 3 BT* S; 4 if(!T) return NULL; 5 if(T->right) 6 { 7 for(S=N->right;S->left;S=S->left); 8 return S; 9 }10 for(S=T;S->parent&&(S->parent->right==S);S=S->parent);11 return S->parent;12 }
Correspondingly, the forward of a node X under the central sequential records is the largest of all nodes (node values) smaller than X. There are also two cases:
Scenario 1: If the left subtree of node X is not empty, the precursor of node X is the rightmost node in the left subtree.
Case 2: The left subtree of node X is empty, and the successor of node X is Y. Then Y is the lowest ancestor node of X, and the right son of Y is also the ancestor of x (x itself can also be seen as the ancestor of X)
1 BT* TreePredecessor (BT* T) 2 { 3 BT * P; 5 if (!T) return NULL; 6 if (T->left) { 7 for (P = T->left; P->right; P = P->right); 8 return P; 9 }11 for (P = t; P->parent && (P->parent->left == P); P = P->parent);12 return P->parent;13 }
Here is a detailed article on bloghttp: // blog.csdn.net/markcnsc/article/details/8566466