public class Solution {
TreeNode lastLeft;
TreeNode ans;
public TreeNode inorderSuccessor(TreeNode root, TreeNode p) {
helper(root, p);
return ans;
}
public void helper(TreeNode root, TreeNode target) {
if (root == null)
return;
if (root == target) {
// Case 1 -> if right subtree exists ,
// then ans is smallest node from that subtree
if (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 node
else
ans = lastLeft;
} else {
if (target.val > root.val)
helper(root.right, target);
else {
lastLeft = root;
helper(root.left, target);
}
}
}
}