Created
April 15, 2022 07:48
-
-
Save Raghav2211/0458576a73e84abec4acf4425dfc4075 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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