-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfind_LCA.java
More file actions
51 lines (44 loc) · 1.6 KB
/
find_LCA.java
File metadata and controls
51 lines (44 loc) · 1.6 KB
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
//Write a program to find the least common ancestor in a tree.
public class find_LCA { // BST
static node findLCA(node root, int n1, int n2) {
if (root == null)
return null;
if (n1 < root.data && n2 < root.data)
return findLCA(root.left, n1, n2);
else if (n1 > root.data && n2 > root.data)
return findLCA(root.right, n1, n2);
else
return root;
}
static void inOrder(node root) {
if (root == null)
return;
inOrder(root.left);
System.out.print(root.data + " ");
inOrder(root.right);
}
public static void main(String[] args) {
node root = new node(10);
root.left = new node(11);
root.right = new node(12);
root.left.left = new node(13);
root.left.right = new node(14);
root.right.left = new node(15);
root.right.right = new node(16);
root.left.left.left = new node(17);
root.left.left.right = new node(18);
root.left.right.left = new node(19);
root.left.right.right = new node(20);
root.right.left.left = new node(21);
root.right.left.right = new node(22);
root.right.right.left = new node(23);
root.right.right.right = new node(24);
System.out.println("In-order traversal of BST:");
inOrder(root);
System.out.println();
int n1 = 5, n2 = 15;
node lca = findLCA(root, n1, n2);
System.out.println("Lowest Common Ancestor of " + n1 + " and " + n2 + ": " +
(lca != null ? lca.data : "Not found"));
}
}