Kth Smallest Element in a BST LeetCode Solution

Here, We see Kth Smallest Element in a BST LeetCode Solution. This Leetcode problem is done in many programming languages like C++, Java, JavaScript, Python, etc. with different approaches.

List of all LeetCode Solution

Problem Statement

Given the `root` of a binary search tree, and an integer `k`, return the `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

Kth Smallest Element in a BST LeetCode SolutionC++

``````class Solution {
public:
void preOrderTraversal(TreeNode* root, vector<int> &v){
if(root == NULL)    return;
v.push_back(root->val);
preOrderTraversal(root->left, v);
preOrderTraversal(root->right, v);
}
int kthSmallest(TreeNode* root, int k) {
vector<int> v;
preOrderTraversal(root, v);
sort(v.begin(), v.end());
return v[k-1];
}
};```Code language: PHP (php)```

Kth Smallest Element in a BST LeetCode SolutionJava

``````class Solution {
List<Integer> values = new ArrayList<>();
public int kthSmallest(TreeNode root, int k) {
inorder(root);
return values.get(k - 1);
}

private void inorder(TreeNode root) {
if (root == null) {
return;
}
inorder(root.left);
inorder(root.right);
}
}```Code language: PHP (php)```

Kth Smallest Element in a BST SolutionJavaScript

``````var kthSmallest = function(root, k) {
let vals = [];
(function dfs(node) {
if (vals.length !=k) {
if(node.left) dfs(node.left);
vals.push(node.val);
if (node.right) dfs(node.right);
}
})(root)
return vals[k-1]
};```Code language: JavaScript (javascript)```

Kth Smallest Element in a BST SolutionPython

``````class Solution(object):
def kthSmallest(self, root, k):
values = []
self.inorder(root, values)
return values[k - 1]

def inorder(self, root, values):
if root is None:
return
self.inorder(root.left, values)
values.append(root.val)
self.inorder(root.right, values)``````
Scroll to Top