018 given a node of the Binary Search Tree, write an algorithm to find its "Next" Node "(keep it up)
Given a node of the Binary Search Tree, write an algorithm to search for its "Next" Node (that is, its successor node after the middle order traversal ),
Each node has a link to its father.
The essence of this question is the question of finding successor nodes when a clue-Based Binary Tree is created. There are two scenarios for finding a successor node:
1. If the current node has a right child, the successor node is the leftmost node of the right child.
2. If no right child exists,
If the current node A is the left child of the parent node, the parent node is the successor node.
B. If the current node is the right child of the parent node, find the parent node until the right child of the current node is not the parent node ends.
The parent node is the successor node.
Code:
Struct TreeNode {int data; TreeNode * leftChild; TreeNode * rightChild; TreeNode * parent;}; TreeNode * findContinue (const TreeNode * vNode) {if (vNode = NULL) return NULL; if (vNode-> rightChild! = NULL) {TreeNode * Tmp = vNode-> rightChild; while (Tmp-> leftChild! = NULL) {Tmp = Tmp-> leftChild;} return Tmp;} TreeNode * Cur = vNode; TreeNode * pParent = Cur-> parent; while (pParent! = NULL & pParent-> rightChild = Cur) {Cur = pParent; pParent = pParent-> rightChild;} return pParent ;}