classSolution{public:Node*inorderSuccessor(Node*node){// The successor is somewhere lower in the right subtree.if(node->right!=nullptr){node=node->right;while(node->left!=nullptr)node=node->left;returnnode;}// The successor is somewhere upper in the tree.while(node->parent&&node->parent->left!=node)node=node->parent;returnnode->parent;}};
1 2 3 4 5 6 7 8 910111213141516
classSolution{publicNodeinorderSuccessor(Nodenode){// The successor is somewhere upper in the tree.if(node.right==null){while(node.parent!=null&&node.parent.left!=node)node=node.parent;returnnode.parent;}// The successor is somewhere lower in the right subtree.node=node.right;while(node.left!=null)node=node.left;returnnode;}}