/
LCABST.java
39 lines (35 loc) · 935 Bytes
/
LCABST.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
/*
Please note that it's Function problem i.e.
you need to write your solution in the form of Function(s) only.
Driver Code to call/invoke your function would be added by GfG's Online Judge.*/
/* A Binary Search Tree node */
/* class Node
{
int data;
Node left, right;
Node(int item)
{
data = item;
left = right = null;
}
}*/
//http://practice.geeksforgeeks.org/problems/lowest-common-ancestor-in-a-bst/1
class GfG
{
Node lca(Node node, int n1, int n2) {
Node root = node;
while (root != null) {
if (root.data >= n1 && root.data <= n2) {
return root;
}
if (root.data > n1 && root.data > n2) {
root = root.left;
} else if (root.data < n1 && root.data < n2){
root = root.right;
} else {
break;
}
}
return root;
}
}