forked from prateekshyap/DSA
-
Notifications
You must be signed in to change notification settings - Fork 0
/
FindInorderSuccessor.java
39 lines (33 loc) · 975 Bytes
/
FindInorderSuccessor.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
/*https://practice.geeksforgeeks.org/problems/inorder-successor-in-bst/1*/
class Solution
{
boolean isXLocated;
Node result;
public Node inorderSuccessor(Node root, Node x)
{
isXLocated = false;
result = null;
//recursion call
traverseInOrder(root,x);
return result;
}
public void traverseInOrder(Node root, Node x)
{//till result is not found
if (root != null && result == null)
{
/*recursion*/
traverseInOrder(root.left,x);
//if x is located and result is not found yet
if (isXLocated && result == null)
{
//mark the current node as the result and return
result = root;
return;
}
//if x node is located, mark it
if (root.data == x.data) isXLocated = true;
/*recursion*/
traverseInOrder(root.right,x);
}
}
}