Skip to content

Commit

Permalink
Create FloorOfBST.java
Browse files Browse the repository at this point in the history
  • Loading branch information
harshithasudhakar authored Feb 5, 2025
1 parent 691009a commit 3bfb05c
Showing 1 changed file with 87 additions and 0 deletions.
87 changes: 87 additions & 0 deletions Binary Search Tree/FloorOfBST.java
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;
}
}

0 comments on commit 3bfb05c

Please sign in to comment.