@mach7 So the reason why your teacher's code is so long is because it works for ANY binary tree, not just binary search tree.

Also, here my version of the code that'll work for any binary tree. It's O(N), so not great.

class Solution {
private:
TreeNode* successor(TreeNode* node, TreeNode* p, bool& found) {
if (!node) return node;
TreeNode* l=successor(node->left,p,found);
if (found) return l ? l : node;
if (node==p) found=true;
return successor(node->right,p,found);
}
public:
TreeNode* inorderSuccessor(TreeNode* root, TreeNode* p) {
bool found=false;
return successor(root,p,found);
}
};