Skip to content

Commit 27d5d39

Browse files
committed
Longest Common Ancestor in BST
1 parent 2189a71 commit 27d5d39

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

GEEKSFORGEEKS/BSTLCA.java

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
2+
3+
/**
4+
* @author : Piyush Kumar
5+
* Problem Link : https://practice.geeksforgeeks.org/problems/lowest-common-ancestor-in-a-bst/1
6+
*
7+
*/
8+
class Node {
9+
int data;
10+
Node left, right;
11+
public Node(int data) {
12+
this.data = data;
13+
this.left = this.right = null;
14+
}
15+
}
16+
class BSTLCA
17+
{
18+
//Function to find the lowest common ancestor in a BST.
19+
Node LCA(Node root, int n1, int n2)
20+
{
21+
// code here.
22+
if (root == null) {
23+
return null;
24+
}
25+
if ((root.data < n1) && (root.data < n2) && (root.right != null)) {
26+
return LCA(root.right, n1 , n2);
27+
}
28+
if ((root.data > n1) && (root.data > n2) && (root.left != null)) {
29+
return LCA(root.left, n1 , n2);
30+
}
31+
return root;
32+
}
33+
34+
}

0 commit comments

Comments
 (0)