-
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.
- Loading branch information
1 parent
691009a
commit 3bfb05c
Showing
1 changed file
with
87 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,87 @@ | ||
//{ Driver Code Starts | ||
// Initial Template for Java | ||
|
||
import java.util.*; | ||
import java.lang.*; | ||
import java.math.*; | ||
import java.io.*; | ||
|
||
class Node { | ||
int data; | ||
Node right; | ||
Node left; | ||
|
||
Node(int val) { | ||
data = val; | ||
right = null; | ||
left = null; | ||
} | ||
} | ||
|
||
class GFG { | ||
|
||
public static Node insert(Node tree, int val) { | ||
Node temp = null; | ||
if (tree == null) { | ||
return new Node(val); | ||
} | ||
|
||
if (val < tree.data) { | ||
tree.left = insert(tree.left, val); | ||
} else if (val > tree.data) { | ||
tree.right = insert(tree.right, val); | ||
} | ||
|
||
return tree; | ||
} | ||
|
||
public static void main(String[] args) throws IOException { | ||
Scanner sc = new Scanner(System.in); | ||
int T = sc.nextInt(); | ||
while (T-- > 0) { | ||
Node root = null; | ||
int n = sc.nextInt(); | ||
for (int i = 0; i < n; i++) { | ||
int k = sc.nextInt(); | ||
root = insert(root, k); | ||
} | ||
|
||
int s = sc.nextInt(); | ||
|
||
Solution obj = new Solution(); | ||
int ans = obj.floor(root, s); | ||
System.out.println(ans); | ||
|
||
System.out.println("~"); | ||
} | ||
} | ||
} | ||
|
||
// } Driver Code Ends | ||
|
||
|
||
// User function Template for Java | ||
|
||
class FloorOfBST { | ||
public static int floor(Node root, int x) { | ||
if(root == null){ | ||
return -1; | ||
} | ||
int floor = -1; | ||
while(root!=null){ | ||
if(root.data == x){ | ||
return root.data; | ||
} | ||
if(root.data < x){ | ||
floor = root.data; | ||
root = root.right; | ||
|
||
} | ||
else{ | ||
root = root.left; | ||
} | ||
} | ||
|
||
return floor; | ||
} | ||
} |