```
public TreeNode InorderSuccessor(TreeNode root, TreeNode p) {
TreeNode lastLeft = null;
TreeNode node = root;
while (node != null)
{
if (node == p) break;
else if (p.val <= node.val)
{
lastLeft = node;
node = node.left;
}
else
{
node = node.right;
}
}
if (node == null) return null;
if (node.right == null) return lastLeft;
node = node.right;
while (node.left != null)
{
node = node.left;
}
return node;
}
```