forked from kakarot237/ml-app
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfloor_and_ceil.java
66 lines (52 loc) · 1.21 KB
/
floor_and_ceil.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
58
59
60
61
62
63
64
65
66
// Java program to find ceil of a given value in BST
class Node {
int data;
Node left, right;
Node(int d)
{
data = d;
left = right = null;
}
}
class BinaryTree {
Node root;
// Function to find ceil of a given input in BST.
// If input is more than the max key in BST,
// return -1
int Ceil(Node node, int input)
{
// Base case
if (node == null) {
return -1;
}
// We found equal key
if (node.data == input) {
return node.data;
}
// If root's key is smaller,
// ceil must be in right subtree
if (node.data < input) {
return Ceil(node.right, input);
}
// Else, either left subtree or root
// has the ceil value
int ceil = Ceil(node.left, input);
return (ceil >= input) ? ceil : node.data;
}
// Driver Code
public static void main(String[] args)
{
BinaryTree tree = new BinaryTree();
tree.root = new Node(8);
tree.root.left = new Node(4);
tree.root.right = new Node(12);
tree.root.left.left = new Node(2);
tree.root.left.right = new Node(6);
tree.root.right.left = new Node(10);
tree.root.right.right = new Node(14);
for (int i = 0; i < 16; i++) {
System.out.println(i + " " + tree.Ceil(tree.root, i));
}
}
}
// This code has been done by Pranjal rajput