-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Create 190404-BST_Lowest_common_ancestor.md
- Loading branch information
1 parent
72afcfd
commit 281312c
Showing
1 changed file
with
70 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | ||
} | ||
} | ||
``` |