Skip to content

Commit 247a799

Browse files
authored
Create LCA of BST
1 parent 90cda11 commit 247a799

File tree

1 file changed

+65
-0
lines changed
  • Course 2 - Data Structures in JAVA/Lecture 13 - BST I

1 file changed

+65
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
/*
2+
Given a binary search tree and data of two nodes, find 'LCA' (Lowest Common Ancestor) of the given two nodes in the BST.
3+
LCA of two nodes A and B is the lowest or deepest node which has both A and B as its descendants.
4+
Note:
5+
It is defined that each node is a descendant to itself, so, if there are two nodes X and Y and X has a direct connection from Y, then Y is the lowest common ancestor.
6+
If out of 2 nodes only one node is present, return that node.
7+
If both are not present, return -1.
8+
9+
Input format:
10+
The first line of input contains data of the nodes of the tree in level order form. The data of the nodes of the tree is separated by space. If any node does not have left or right child, take -1 in its place. Since -1 is used as an indication whether the left or right nodes exist, therefore, it will not be a part of the data of any node.
11+
The following line of input contains two integers, denoting the value of data of two nodes of given BST.
12+
13+
Output Format:
14+
The first and only line of output contains the data associated with the lowest common ancestor node.
15+
16+
Constraints:
17+
Time Limit: 1 second
18+
19+
Sample Input 1:
20+
8 5 10 2 6 -1 -1 -1 -1 -1 7 -1 -1
21+
2 10
22+
Sample Output 1:
23+
8
24+
25+
Sample Input 2:
26+
8 5 10 2 6 -1 -1 -1 -1 -1 7 -1 -1
27+
2 6
28+
Sample Output 2:
29+
5
30+
31+
Sample Input 3:
32+
8 5 10 2 6 -1 -1 -1 -1 -1 7 -1 -1
33+
12 78
34+
Sample Output 3:
35+
-1
36+
*/
37+
public class Solution {
38+
39+
/*
40+
* Binary Tree Node class
41+
*
42+
* class BinaryTreeNode<T> { T data; BinaryTreeNode<T> left; BinaryTreeNode<T> right;
43+
*
44+
* public BinaryTreeNode(T data) { this.data = data; } }
45+
*/
46+
47+
48+
49+
public static int getLCA(BinaryTreeNode<Integer> root, int n1, int n2) {
50+
if (root == null)
51+
return -1;
52+
53+
// If both n1 and n2 are smaller than root, then LCA lies in left
54+
if (root.data > n1 && root.data > n2)
55+
return getLCA(root.left, n1, n2);
56+
57+
// If both n1 and n2 are greater than root, then LCA lies in right
58+
if (root.data < n1 && root.data < n2)
59+
return getLCA(root.right, n1, n2);
60+
61+
return root.data;
62+
63+
64+
}
65+
}

0 commit comments

Comments
 (0)