Skip to content

Commit c84c95e

Browse files
authored
Create Elements Between K1 and K2
1 parent c291830 commit c84c95e

File tree

1 file changed

+72
-0
lines changed

1 file changed

+72
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
/*
2+
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).
3+
Print the elements in increasing order.
4+
5+
Input format:
6+
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.
7+
The following line contains two integers, that denote the value of k1 and k2.
8+
9+
Output Format:
10+
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.
11+
12+
Constraints:
13+
Time Limit: 1 second
14+
15+
Sample Input 1:
16+
8 5 10 2 6 -1 -1 -1 -1 -1 7 -1 -1
17+
6 10
18+
Sample Output 1:
19+
6 7 8 10
20+
*/
21+
import java.util.*;
22+
public class Solution {
23+
24+
/* Binary Tree Node class
25+
*
26+
* class BinaryTreeNode<T> {
27+
T data;
28+
BinaryTreeNode<T> left;
29+
BinaryTreeNode<T> right;
30+
31+
public BinaryTreeNode(T data) {
32+
this.data = data;
33+
}
34+
}
35+
*/
36+
37+
private static ArrayList<Integer> arr = new ArrayList<Integer>();
38+
39+
public static void elementsInRangeK1K2(BinaryTreeNode<Integer> root,int k1,int k2)
40+
{
41+
elementsInRangeK1K2Helper(root,k1,k2);
42+
Collections.sort(arr);
43+
for (int i:arr)
44+
System.out.print(i+" ");
45+
}
46+
public static void elementsInRangeK1K2Helper(BinaryTreeNode<Integer> root,int k1,int k2){
47+
48+
//Base case - if root=null
49+
if (root==null)
50+
return;
51+
52+
int rootData=root.data;
53+
if (rootData<k1)
54+
{
55+
elementsInRangeK1K2Helper(root.right,k1,k2);
56+
}
57+
else if (rootData>k2)
58+
{
59+
elementsInRangeK1K2Helper(root.left,k1,k2);
60+
}
61+
else
62+
{
63+
//System.out.print(rootData+" ");
64+
arr.add(rootData);
65+
elementsInRangeK1K2Helper(root.right,k1,k2);
66+
elementsInRangeK1K2Helper(root.left,k1,k2);
67+
}
68+
69+
}
70+
71+
72+
}

0 commit comments

Comments
 (0)