publicclassSolution {TreeNode lastLeft;TreeNode ans;publicTreeNodeinorderSuccessor(TreeNode root,TreeNode p) {helper(root, p);return ans; }publicvoidhelper(TreeNode root,TreeNode target) {if (root ==null)return;if (root == target) {// Case 1 -> if right subtree exists ,// then ans is smallest node from that subtreeif (root.right!=null) {TreeNode temp =root.right;while (temp.left!=null) temp =temp.left; ans = temp; }// Else the answer is the node where we took the last left turn// to reach target nodeelse ans = lastLeft; } else {if (target.val>root.val)helper(root.right, target);else { lastLeft = root;helper(root.left, target); } } }}