Skip to content

Commit cc29446

Browse files
authored
Create LowestCommonAncestorBST.java
In Interviews If Tree Data Structure Is Discussed Then This Is Probably One Of The Most Important Question I Have Solved This Using Recursion
1 parent e3115e3 commit cc29446

File tree

1 file changed

+13
-0
lines changed

1 file changed

+13
-0
lines changed

LowestCommonAncestorBST.java

+13
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
//Given a binary search tree (BST), find the lowest common ancestor (LCA) node of two given nodes in the BST.
2+
3+
4+
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
5+
if(p.val<root.val && q.val<root.val){
6+
return lowestCommonAncestor(root.left,p,q);
7+
}
8+
else if(p.val>root.val && q.val>root.val){
9+
return lowestCommonAncestor(root.right,p,q);
10+
}
11+
12+
return root;
13+
}

0 commit comments

Comments
 (0)