-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBinary Search Trees:LCA of BST
58 lines (46 loc) · 1.17 KB
/
Binary Search Trees:LCA of BST
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
public class Solution {
/* Binary Tree Node class
*
* class BinaryTreeNode<T> {
T data;
BinaryTreeNode<T> left;
BinaryTreeNode<T> right;
public BinaryTreeNode(T data) {
this.data = data;
}
}
*/
public static int lcaInBST(BinaryTreeNode<Integer> root , int a , int b){
// Write your code here
if(root==null)
return -1;
int c=-1;
if(root.data==a || root.data==b)
return root.data;
else if(a<root.data && b>root.data || a>root.data && b<root.data)
{
c=lcaInBST(root.left,a,b);
int d=lcaInBST(root.right,a,b);
if(c==-1 && d==-1)
return -1;
else if(c==-1 && d!=-1)
return d;
else if(c!=-1 && d==-1)
return c;
else
return root.data;
}
else if(a<root.data &&b<root.data)
{
c=lcaInBST(root.left,a,b);
}
else if(a>root.data &&b>root.data)
{
c=lcaInBST(root.right,a,b);
}
if(c!=-1)
return c;
else
return -1;
}
}