-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathElementsBetweenK1AndK2.java
More file actions
60 lines (51 loc) · 1.68 KB
/
ElementsBetweenK1AndK2.java
File metadata and controls
60 lines (51 loc) · 1.68 KB
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
// Elements Between K1 and K2
// Send Feedback
// Given a Binary Search Tree and two integers k1 and k2, find and print the
// elements which are in range k1 and k2 (both inclusive).
// Print the elements in increasing order.
// Input format:
// The first line of input contains data of the nodes of the tree in level order
// form. The data of the nodes of the tree is separated by space. If any node
// does not have left or right child, take -1 in its place. Since -1 is used as
// an indication whether the left or right nodes exist, therefore, it will not
// be a part of the data of any node.
// The following line contains two integers, that denote the value of k1 and k2.
// Output Format:
// The first and only line of output prints the elements which are in range k1
// and k2 (both inclusive). Print the elements in increasing order.
// Constraints:
// Time Limit: 1 second
// Sample Input 1:
// 8 5 10 2 6 -1 -1 -1 -1 -1 7 -1 -1
// 6 10
// Sample Output 1:
// 6 7 8 10
public class Solution {
/*
* Binary Tree Node class
*
* class BinaryTreeNode<T> {
* T data;
* BinaryTreeNode<T> left;
* BinaryTreeNode<T> right;
*
* public BinaryTreeNode(T data) {
* this.data = data;
* }
* }
*/
public static void elementsInRangeK1K2(BinaryTreeNode<Integer> root, int k1, int k2) {
if (root == null) {
return;
}
if (root.data > k1) {
elementsInRangeK1K2(root.left, k1, k2);
}
if (root.data >= k1 && root.data <= k2) {
System.out.print(root.data + " ");
}
if (root.data <= k2) {
elementsInRangeK1K2(root.right, k1, k2);
}
}
}