-
Notifications
You must be signed in to change notification settings - Fork 35
/
BSTFindFloorAndCeil.java
57 lines (48 loc) · 1.01 KB
/
BSTFindFloorAndCeil.java
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
package bst;
public class BSTFindFloorAndCeil {
public static void main(String[] args) {
Node root = new Node(50);
root.left = new Node(30);
root.right = new Node(70);
root.left.left = new Node(20);
root.left.right = new Node(40);
root.right.left = new Node(60);
root.right.right = new Node(80);
Node res = findCeil(root, 4);
if(res == null)
System.out.println("-1");
else
System.out.println(res.key);
}
private static Node findfloor(Node root, int x) {
Node curr = root;
Node res = null;
while(curr != null) {
if(curr.key == x)
return curr;
if(curr.key < x) {
res = curr;
curr = curr.right;
}
else if (curr.key > x)
curr = curr.left;
}
return res;
}
private static Node findCeil(Node root, int x) {
Node curr = root;
Node res = null;
while(curr != null) {
if(curr.key == x)
return curr;
if(curr.key < x) {
curr = curr.right;
}
else if(curr.key > x) {
res = curr;
curr = curr.left;
}
}
return res;
}
}