|
1 | 1 | package com.thealgorithms.datastructures.trees; |
2 | 2 |
|
3 | 3 | import static org.junit.jupiter.api.Assertions.assertEquals; |
4 | | - |
5 | 4 | import org.junit.jupiter.api.Test; |
6 | 5 |
|
7 | | -public class KthSmallestElementBSTTest { |
| 6 | +class KthSmallestElementInBSTTest { |
8 | 7 |
|
9 | | - @Test |
10 | | - void simpleTest() { |
| 8 | + private BinaryTree.Node createSampleTree() { |
| 9 | + /* |
| 10 | + 5 |
| 11 | + / \ |
| 12 | + 3 7 |
| 13 | + / \ / \ |
| 14 | + 2 4 6 8 |
| 15 | + */ |
11 | 16 | BinaryTree.Node root = new BinaryTree.Node(5); |
12 | 17 | root.left = new BinaryTree.Node(3); |
13 | 18 | root.right = new BinaryTree.Node(7); |
| 19 | + root.left.left = new BinaryTree.Node(2); |
| 20 | + root.left.right = new BinaryTree.Node(4); |
| 21 | + root.right.left = new BinaryTree.Node(6); |
| 22 | + root.right.right = new BinaryTree.Node(8); |
14 | 23 |
|
15 | | - assertEquals(3, KthSmallestElementInBST.kthSmallest(root, 1)); |
| 24 | + return root; |
| 25 | + } |
| 26 | + |
| 27 | + @Test |
| 28 | + void testSmallestElement() { |
| 29 | + BinaryTree.Node root = createSampleTree(); |
| 30 | + assertEquals(2, KthSmallestElementInBST.kthSmallest(root, 1)); |
| 31 | + } |
| 32 | + |
| 33 | + @Test |
| 34 | + void testRootElement() { |
| 35 | + BinaryTree.Node root = createSampleTree(); |
| 36 | + assertEquals(5, KthSmallestElementInBST.kthSmallest(root, 4)); |
| 37 | + } |
| 38 | + |
| 39 | + @Test |
| 40 | + void testRightSubtreeElement() { |
| 41 | + BinaryTree.Node root = createSampleTree(); |
| 42 | + assertEquals(8, KthSmallestElementInBST.kthSmallest(root, 7)); |
| 43 | + } |
| 44 | + |
| 45 | + @Test |
| 46 | + void testSingleNodeTree() { |
| 47 | + BinaryTree.Node root = new BinaryTree.Node(10); |
| 48 | + assertEquals(10, KthSmallestElementInBST.kthSmallest(root, 1)); |
| 49 | + } |
| 50 | + |
| 51 | + @Test |
| 52 | + void testInvalidK() { |
| 53 | + BinaryTree.Node root = createSampleTree(); |
| 54 | + assertEquals(-1, KthSmallestElementInBST.kthSmallest(root, 10)); |
16 | 55 | } |
17 | 56 | } |
0 commit comments