Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 0 additions & 30 deletions src/KthSmallestElementInaBST230.java

This file was deleted.

28 changes: 28 additions & 0 deletions src/main/java/com/leetcode/medium/KthSmallestElementInABST230.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
// Tags: Tree, Binary Search Tree, DFS
package com.leetcode.medium;

import com.leetcode.datastructure.TreeNode;

import java.util.ArrayList;
import java.util.List;

public class KthSmallestElementInABST230 {
private void inorder(TreeNode node, List<Integer> res) {
if (node == null) {
return;
}
inorder(node.left, res);
res.add(node.val);
inorder(node.right, res);
}

/*
Time complexity : O(N) to build a traversal.
Space complexity : O(N) to keep an inorder traversal.
*/
public int kthSmallest(TreeNode root, int k) {
List<Integer> values = new ArrayList<>();
inorder(root, values);
return values.get(k - 1);
}
Comment on lines +26 to +27

Copilot AI Nov 1, 2025

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The method lacks validation for the parameter k. If k is less than 1 or greater than the number of nodes in the tree, this will throw an IndexOutOfBoundsException. Consider adding validation to check that k is within the valid range (1 <= k <= tree size) and throw a more meaningful exception (e.g., IllegalArgumentException) with a descriptive error message.

Suggested change
return values.get(k - 1);
}
if (k < 1 || k > values.size()) {
throw new IllegalArgumentException("Parameter k is out of bounds. Valid range: 1 <= k <= " + values.size() + ", but got k = " + k);
}
return values.get(k - 1);

Copilot uses AI. Check for mistakes.
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
package com.leetcode.medium;

import com.leetcode.datastructure.TreeNode;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.assertEquals;

public class KthSmallestElementInABST230Test {
private KthSmallestElementInABST230 solution;

@BeforeEach
void setUp() {
solution = new KthSmallestElementInABST230();
}

@Test
void testKthSmallest_Example1() {
TreeNode root = new TreeNode(3,
new TreeNode(1, null, new TreeNode(2)),
new TreeNode(4));

int k = 1;

int expected = 1;
int result = solution.kthSmallest(root, k);

assertEquals(expected, result);
}

@Test
void testKthSmallest_Example2() {
TreeNode root = new TreeNode(5,
new TreeNode(3,
new TreeNode(2,
new TreeNode(1),
null),
new TreeNode(4)),
new TreeNode(6));

int k = 3;

int expected = 3;
int result = solution.kthSmallest(root, k);

assertEquals(expected, result);
}
}