# D & F learning Data Structure series-predecessor and successor

Source: Internet
Author: User

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

Related Keywords:

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

## A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

• #### Sales Support

1 on 1 presale consultation

• #### After-Sales Support

24/7 Technical Support 6 Free Tickets per Quarter Faster Response

• Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.