-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathProblem_7.java
More file actions
67 lines (56 loc) · 1.9 KB
/
Copy pathProblem_7.java
File metadata and controls
67 lines (56 loc) · 1.9 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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package trees.binarySearchTree;
// Problem Title -> The Lowest common ancestor in bst
public class Problem_7 {
// A binary tree node
static class Node {
int data;
Node left, right;
Node(int item) {
data = item;
left = right = null;
}
}
Node root;
/*
* Function to find LCA of n1 and n2.
* The function assumes that both n1 and n2 are present in BST
*/
static Node lca(Node root, int n1, int n2) {
while (root != null) {
// If both n1 and n2 are smaller than root, then LCA lies in left
if (root.data > n1 &&
root.data > n2)
root = root.left;
// If both n1 and n2 are greater than root, then LCA lies in right
else if (root.data < n1 &&
root.data < n2)
root = root.right;
else
break;
}
return root;
}
/* Driver program to test lca() */
public static void main(String args[]) {
// Let us construct the BST shown in the above figure
Problem_7 tree = new Problem_7();
tree.root = new Node(20);
tree.root.left = new Node(8);
tree.root.right = new Node(22);
tree.root.left.left = new Node(4);
tree.root.left.right = new Node(12);
tree.root.left.right.left = new Node(10);
tree.root.left.right.right = new Node(14);
int n1 = 10, n2 = 14;
Node t = Problem_7.lca(tree.root, n1, n2);
System.out.println("LCA of " + n1 + " and " + n2 + " is " + t.data);
n1 = 14;
n2 = 8;
t = Problem_7.lca(tree.root, n1, n2);
System.out.println("LCA of " + n1 + " and " + n2 + " is " + t.data);
n1 = 10;
n2 = 22;
t = Problem_7.lca(tree.root, n1, n2);
System.out.println("LCA of " + n1 + " and " + n2 + " is " + t.data);
}
}