230. Kth Smallest Element in a BST
Given the root of a binary search tree, and an integer k, return the k t h k^{th} kth smallest value (1-indexed) of all the values of the nodes in the tree.
Example 1:
Input: root = [3,1,4,null,2], k = 1
Output: 1
Example 2:
Input: root = [5,3,6,2,4,null,null,1], k = 3
Output: 3
Constraints:
- The number of nodes in the tree is n.
- 1 < = k < = n < = 1 0 4 1 <= k <= n <= 10^4 1<=k<=n<=104
- 0 < = N o d e . v a l < = 1 0 4 0 <= Node.val <= 10^4 0<=Node.val<=104
From: LeetCode
Link: 230. Kth Smallest Element in a BST
Solution:
Ideas:
Here’s how the algorithm will work:
- Perform an in-order traversal of the BST.
- As you traverse the nodes, keep a count of the nodes visited.
- When the count becomes equal to k, that node’s value is the kth smallest. current node and the previous node.
Code:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
typedef struct {
int count;
int value;
} Result;
void inOrderTraversal(struct TreeNode* root, int k, Result* res) {
if (root == NULL || res->count == k) return;
inOrderTraversal(root->left, k, res);
if (++res->count == k) {
res->value = root->val;
}
inOrderTraversal(root->right, k, res);
}
int kthSmallest(struct TreeNode* root, int k) {
Result res = {
0, 0};
inOrderTraversal(root, k, &res);
return res.value;
}