Skip to content

Commit 1849310

Browse files
author
Krishnan M
committed
added binarysearchtree
1 parent f57ffa9 commit 1849310

File tree

2 files changed

+304
-0
lines changed

2 files changed

+304
-0
lines changed
Lines changed: 202 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,202 @@
1+
package com.thealgorithms.tree;
2+
3+
4+
import java.util.Arrays;
5+
6+
/**
7+
* Binary Search Tree (BST) implementation in Java.
8+
* Supports insertion, traversal (preorder, inorder, postorder),
9+
* balance checking, and pretty display of the tree structure.
10+
*
11+
* Author: Udaya Krishnan M
12+
* GitHub: https://github.com/UdayaKrishnanM/
13+
*/
14+
public class BinarySearchTree {
15+
16+
/**
17+
* Node class representing each element in the BST.
18+
*/
19+
class Node {
20+
private int value;
21+
private Node left;
22+
private Node right;
23+
private int height;
24+
25+
public Node(int value) {
26+
this.value = value;
27+
}
28+
29+
public int getValue() {
30+
return value;
31+
}
32+
}
33+
34+
private Node root;
35+
36+
public BinarySearchTree() {
37+
// Empty constructor
38+
}
39+
40+
/**
41+
* Returns the height of a node.
42+
*/
43+
public int height(Node node) {
44+
return node == null ? -1 : node.height;
45+
}
46+
47+
/**
48+
* Checks if the BST is empty.
49+
*/
50+
public boolean isEmpty() {
51+
return root == null;
52+
}
53+
54+
/**
55+
* Inserts a value into the BST.
56+
*/
57+
public void insert(int value) {
58+
root = createBST(root, value);
59+
}
60+
61+
/**
62+
* Recursively creates the BST based on the value.
63+
*/
64+
public Node createBST(Node node, int value) {
65+
if (node == null) {
66+
return new Node(value);
67+
}
68+
69+
if (value < node.value) {
70+
node.left = createBST(node.left, value);
71+
} else if (value > node.value) {
72+
node.right = createBST(node.right, value);
73+
}
74+
75+
node.height = Math.max(height(node.left), height(node.right)) + 1;
76+
return node;
77+
}
78+
79+
/**
80+
* Populates the BST with an array of values.
81+
*/
82+
public void populate(int[] nums) {
83+
for (int num : nums) {
84+
insert(num);
85+
}
86+
}
87+
88+
/**
89+
* Checks if the BST is balanced.
90+
*/
91+
public boolean balanced() {
92+
return balanced(root);
93+
}
94+
95+
private boolean balanced(Node node) {
96+
if (node == null) return true;
97+
98+
int balanceFactor = Math.abs(height(node.left) - height(node.right));
99+
System.out.println("Node value: " + node.value + " | Balance Factor: " + balanceFactor);
100+
101+
return balanceFactor <= 1 && balanced(node.left) && balanced(node.right);
102+
}
103+
104+
/**
105+
* Displays the tree in a structured format.
106+
*/
107+
public void prettyDisplay() {
108+
prettyDisplay(root, 0);
109+
}
110+
111+
private void prettyDisplay(Node node, int level) {
112+
if (node == null) return;
113+
114+
prettyDisplay(node.right, level + 1);
115+
116+
if (level != 0) {
117+
for (int i = 0; i < level - 1; i++) {
118+
System.out.print("|\t");
119+
}
120+
System.out.println("|----> " + node.value);
121+
} else{
122+
System.out.println(node.value);
123+
}
124+
prettyDisplay(node.left, level + 1);
125+
}
126+
127+
/**
128+
* Populates the BST in a balanced way using sorted array.
129+
*/
130+
public void populateSorted(int[] nums) {
131+
Arrays.sort(nums);
132+
populateSorted(nums, 0, nums.length);
133+
}
134+
135+
private void populateSorted(int[] nums, int start, int end) {
136+
if (start >= end) return;
137+
138+
int mid = start + (end - start) / 2;
139+
insert(nums[mid]);
140+
populateSorted(nums, start, mid);
141+
populateSorted(nums, mid + 1, end);
142+
}
143+
144+
/**
145+
* Preorder traversal: Root -> Left -> Right
146+
*/
147+
public void preOrder() {
148+
preOrder(root);
149+
System.out.println();
150+
}
151+
152+
private void preOrder(Node node) {
153+
if (node == null) return;
154+
System.out.print(node.value + " ");
155+
preOrder(node.left);
156+
preOrder(node.right);
157+
}
158+
159+
/**
160+
* Inorder traversal: Left -> Root -> Right
161+
*/
162+
public void inOrder(){
163+
inOrder(root);
164+
System.out.println();
165+
}
166+
167+
private void inOrder(Node node) {
168+
if (node == null) return;
169+
inOrder(node.left);
170+
System.out.print(node.value + " (height: " + node.height + ") | ");
171+
inOrder(node.right);
172+
}
173+
174+
/**
175+
* Postorder traversal: Left -> Right -> Root
176+
*/
177+
public void postOrder() {
178+
postOrder(root);
179+
System.out.println();
180+
}
181+
182+
private void postOrder(Node node) {
183+
if (node == null) return;
184+
postOrder(node.left);
185+
postOrder(node.right);
186+
System.out.print(node.value + " ");
187+
}
188+
189+
/**
190+
* Displays the tree with node relationships.
191+
*/
192+
public void display() {
193+
display(root, "Root Node: ");
194+
}
195+
196+
private void display(Node node, String details) {
197+
if (node == null) return;
198+
System.out.println(details + node.value);
199+
display(node.left, "Left child of " + node.value + ": ");
200+
display(node.right, "Right child of " + node.value + ": ");
201+
}
202+
}
Lines changed: 102 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,102 @@
1+
package com.thealgorithms.tree;
2+
3+
import static org.junit.jupiter.api.Assertions.*;
4+
5+
import org.junit.jupiter.api.BeforeEach;
6+
import org.junit.jupiter.api.Test;
7+
8+
/**
9+
* Unit tests for the Binary Search Tree (BST) implementation.
10+
* Covers insertion, traversal, balance checking, and display logic.
11+
*
12+
* Author: Udaya Krishnan M
13+
* GitHub: https://github.com/UdayaKrishnanM/
14+
*/
15+
class BinarySearchTreeTest {
16+
17+
private BinarySearchTree bst;
18+
private final int[] values = {30, 20, 40, 10, 25, 35, 50};
19+
20+
/**
21+
* Initializes the BST before each test with a predefined set of values.
22+
*/
23+
@BeforeEach
24+
void setUp() {
25+
bst = new BinarySearchTree();
26+
bst.populate(values);
27+
}
28+
29+
/**
30+
* Verifies that the BST is not empty after insertion.
31+
*/
32+
@Test
33+
void testBSTIsNotEmpty() {
34+
assertFalse(bst.isEmpty(), "BST should not be empty after insertion");
35+
}
36+
37+
/**
38+
* Tests the height calculation of the root node.
39+
*/
40+
@Test
41+
void testRootHeight() {
42+
int expectedHeight = 2;
43+
assertEquals(expectedHeight, bst.height(bst.createBST(null, 30)), "Height of root node should be 2");
44+
}
45+
46+
47+
/**
48+
* Tests if the BST is balanced.
49+
*/
50+
@Test
51+
void testBalancedTree() {
52+
assertTrue(bst.balanced(), "BST should be balanced with given values");
53+
}
54+
55+
/**
56+
* Tests inorder traversal output.
57+
*/
58+
@Test
59+
void testInOrderTraversal() {
60+
// Expected sorted order
61+
bst.inOrder(); // You can redirect System.out to capture output if needed
62+
assertTrue(true, "Inorder traversal executed successfully");
63+
}
64+
65+
/**
66+
* Tests preorder traversal output.
67+
*/
68+
@Test
69+
void testPreOrderTraversal() {
70+
bst.preOrder();
71+
assertTrue(true, "Preorder traversal executed successfully");
72+
}
73+
74+
/**
75+
* Tests postorder traversal output.
76+
*/
77+
@Test
78+
void testPostOrderTraversal() {
79+
bst.postOrder();
80+
assertTrue(true, "Postorder traversal executed successfully");
81+
}
82+
83+
/**
84+
* Tests pretty display of the BST.
85+
*/
86+
@Test
87+
void testPrettyDisplay() {
88+
bst.prettyDisplay();
89+
assertTrue(true, "Pretty display executed successfully");
90+
}
91+
92+
/**
93+
* Tests balanced population using sorted array.
94+
*/
95+
@Test
96+
void testPopulateSorted() {
97+
int[] sortedValues = {10, 20, 30, 40, 50};
98+
BinarySearchTree sortedBST = new BinarySearchTree();
99+
sortedBST.populateSorted(sortedValues);
100+
assertTrue(sortedBST.balanced(), "BST populated with sorted array should be balanced");
101+
}
102+
}

0 commit comments

Comments
 (0)