Last updated on October 25th, 2024 at 10:21 pm
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
Topics
Binary Search, Tree
Companies
Bloomberg, Google, Uber
Level of Question
Medium
Kth Smallest Element in a BST LeetCode Solution
Table of Contents
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
1. Kth Smallest Element in a BST LeetCode Solution C++
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]; } };
2. Kth Smallest Element in a BST LeetCode Solution Java
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); values.add(root.val); inorder(root.right); } }
3. Kth Smallest Element in a BST Solution JavaScript
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] };
4. Kth Smallest Element in a BST Solution Python
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)