Skip to content

Instantly share code, notes, and snippets.

@Raghav2211
Created April 15, 2022 07:48
Show Gist options
  • Save Raghav2211/0458576a73e84abec4acf4425dfc4075 to your computer and use it in GitHub Desktop.
Save Raghav2211/0458576a73e84abec4acf4425dfc4075 to your computer and use it in GitHub Desktop.
class Node{
int data;
Node left,right;
Node(int d){
data=d;
left=right=null;
}
}
class Solution
{
public Node inorderSuccessor(Node root, Node x) {
Node successorNode = null;
if (x.right != null) {
successorNode = minNodeOnLeft(x.right);
} else {
successorNode = minNodeOnRightNull(root, x, root.data > x.data ? root : x);
}
return successorNode.data == x.data ? null : successorNode;
}
Node minNodeOnRightNull(Node node, Node search, Node max) {
if (node.data == search.data) {
return max;
}
if (search.data < node.data) max = node;
return search.data < node.data
? minNodeOnRightNull(node.left, search, max)
: minNodeOnRightNull(node.right, search, max);
}
Node minNodeOnLeft(Node node) {
if (node == null) {
return null;
}
Node minNode = minNodeOnLeft(node.left);
return minNode == null ? node : minNode;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment