Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 81af3aa

Browse files
committedFeb 17, 2025
Add solution #230
1 parent 36cd5b9 commit 81af3aa

File tree

2 files changed

+35
-0
lines changed

2 files changed

+35
-0
lines changed
 

‎README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -203,6 +203,7 @@
203203
226|[Invert Binary Tree](./0226-invert-binary-tree.js)|Easy|
204204
228|[Summary Ranges](./0228-summary-ranges.js)|Easy|
205205
229|[Majority Element II](./0229-majority-element-ii.js)|Medium|
206+
230|[Kth Smallest Element in a BST](./0230-kth-smallest-element-in-a-bst.js)|Medium|
206207
231|[Power of Two](./0231-power-of-two.js)|Easy|
207208
232|[Implement Queue using Stacks](./0232-implement-queue-using-stacks.js)|Easy|
208209
233|[Number of Digit One](./0233-number-of-digit-one.js)|Hard|
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
/**
2+
* 230. Kth Smallest Element in a BST
3+
* https://leetcode.com/problems/kth-smallest-element-in-a-bst/
4+
* Difficulty: Medium
5+
*
6+
* Given the root of a binary search tree, and an integer k, return the kth smallest value
7+
* (1-indexed) of all the values of the nodes in the tree.
8+
*/
9+
10+
/**
11+
* Definition for a binary tree node.
12+
* function TreeNode(val, left, right) {
13+
* this.val = (val===undefined ? 0 : val)
14+
* this.left = (left===undefined ? null : left)
15+
* this.right = (right===undefined ? null : right)
16+
* }
17+
*/
18+
/**
19+
* @param {TreeNode} root
20+
* @param {number} k
21+
* @return {number}
22+
*/
23+
var kthSmallest = function(root, k) {
24+
const result = [];
25+
dfs(root);
26+
return result[k - 1];
27+
28+
function dfs(node) {
29+
if (!node || result.length > k) return null;
30+
dfs(node.left);
31+
result.push(node.val);
32+
dfs(node.right);
33+
}
34+
};

0 commit comments

Comments
 (0)
Please sign in to comment.