class Solution {public:TreeNode* inorderSuccessor(TreeNode* root, TreeNode* p) {TreeNode *successor = nullptr;/* p节点有右子树就从p节点右子树开始搜索 */if (p->right != nullptr) {successor = p->right;while (successor->left != nullptr) {successor = successor->left;}return successor;}/* 从二叉搜索树当中查找p节点的父节点 */TreeNode *node = root;while (node != nullptr) {if (node->val > p->val) {/* 如果p在左子树,后继节点会是当前节点或者当前左子树中的节点 */successor = node;node = node->left;} else {/* 当前值小于p的val 说明不能满足后继节点的大于pval的条件 */node = node->right;}}return successor;}};
设计一个算法,找出二叉搜索树中指定节点的“下一个”节点(也即中序后继)。如果指定节点没有对应的“下一个”节点,则返回null。
这里首先对 p节点的右子树的最左子节点,如果存在右子树就可以在右子树有后序节点;如果右子树为空,需要在二叉搜索树当中的查找p节点的父节点,
