package org.wesome.dsalgo;
import lombok.Data;
import java.util.Objects;
public class BinarySearchTree {
Node root;
void printKeysInRange(Node node, int key1, int key2) {
if (node == null) {
return;
}
/* If root->data is greater than key1, then only we can get o/p keys in left subtree */
if (key1 < node.data) {
printKeysInRange(node.left, key1, key2);
}
/* if root's data lies in range, then prints root's data */
if (key1 <= node.data && key2 >= node.data) {
System.out.print(node.data + " ");
}
/* If root->data is smaller than key2, then only we can get o/p keys in right subtree */
if (key2 > node.data) {
printKeysInRange(node.right, key1, key2);
}
}
void insert(int data) {
System.out.println("BinarySearchTree.insert data = " + data);
root = insert(root, data);
}
Node insert(Node root, int data) {
if (Objects.isNull(root)) {
Node tempNode = new Node(data);
return tempNode;
}
if (data > root.data) {
root.right = insert(root.right, data);
} else {
root.left = insert(root.left, data);
}
return root;
}
}
@Data
class Node {
int data;
Node left, right;
public Node(int data) {
this.data = data;
left = right = null;
}
}
package org.wesome.dsalgo;
import org.junit.jupiter.api.Test;
public class BinarySearchTreeTest {
@Test
void printKeysInRangeTest() {
BinarySearchTree binarySearchTree = new BinarySearchTree();
binarySearchTree.insert(4);
binarySearchTree.insert(2);
binarySearchTree.insert(1);
binarySearchTree.insert(3);
binarySearchTree.insert(6);
binarySearchTree.insert(5);
binarySearchTree.insert(7);
binarySearchTree.printKeysInRange(binarySearchTree.root, Integer.MIN_VALUE, Integer.MAX_VALUE);
}
}
plugins {
id 'java'
id "io.freefair.lombok" version "6.2.0"
}
group = 'org.wesome'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = JavaVersion.VERSION_1_8
configurations {
compileOnly {
extendsFrom annotationProcessor
}
}
repositories {
mavenCentral()
}
dependencies {
testImplementation 'org.junit.jupiter:junit-jupiter:5.6.2'
}
test {
useJUnitPlatform()
}