Skip to content

Commit

Permalink
Create 190404-BST_Lowest_common_ancestor.md
Browse files Browse the repository at this point in the history
  • Loading branch information
super-fishz authored Apr 4, 2019
1 parent 72afcfd commit 281312c
Showing 1 changed file with 70 additions and 0 deletions.
70 changes: 70 additions & 0 deletions PS/190404-BST_Lowest_common_ancestor.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
# [Binary Search Tree : Lowest Common Ancestor](https://www.hackerrank.com/challenges/binary-search-tree-lowest-common-ancestor/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=trees)
## Problem
## Solve
```java
import java.util.*;
import java.io.*;

class Node {
Node left;
Node right;
int data;

Node(int data) {
this.data = data;
left = null;
right = null;
}
}

class Solution {

/*
class Node
int data;
Node left;
Node right;
*/
public static Node lca(Node root, int v1, int v2) {
if(root.data < v1 && root.data < v2){
return lca(root.right,v1,v2);
}
if(root.data > v1 && root.data > v2){
return lca(root.left,v1,v2);
}

return root;
}

public static Node insert(Node root, int data) {
if(root == null) {
return new Node(data);
} else {
Node cur;
if(data <= root.data) {
cur = insert(root.left, data);
root.left = cur;
} else {
cur = insert(root.right, data);
root.right = cur;
}
return root;
}
}

public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int t = scan.nextInt();
Node root = null;
while(t-- > 0) {
int data = scan.nextInt();
root = insert(root, data);
}
int v1 = scan.nextInt();
int v2 = scan.nextInt();
scan.close();
Node ans = lca(root,v1,v2);
System.out.println(ans.data);
}
}
```

0 comments on commit 281312c

Please sign in to comment.