Physical Address
304 North Cardinal St.
Dorchester Center, MA 02124
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
Constraints:
n
.1 <= k <= n <= 104
0 <= Node.val <= 104
Follow up: If the BST is modified often (i.e., we can do insert and delete operations) and you need to find the kth smallest frequently, how would you optimize?
def findNode(node, res):
if len(res) > 1:
return
if node.left:
findNode(node.left, res)
res[0] -= 1
if res[0] == 0:
res.append(node.val)
return
if node.right:
findNode(node.right, res)
res = [k]
findNode(root, res)
return res[1]
def kthSmallest(self, root, k):
self.k = k
self.res = None
self.helper(root)
return self.res
def helper(self, node):
if not node:
return
self.helper(node.left)
self.k -= 1
if self.k == 0:
self.res = node.val
return
self.helper(node.right)
int kthSmallest(TreeNode* root, int k) {
return find(root, k);
}
int find(TreeNode* root, int& k) {
if (root) {
int x = find(root->left, k);
return !k ? x : !--k ? root->val : find(root->right, k);
}
}
In our experience, we suggest you solve this Kth Smallest Element in a BST LeetCode Solution and gain some new skills from Professionals completely free and we assure you will be worth it.
If you are stuck anywhere between any coding problem, just visit Queslers to get the Kth Smallest Element in a BST LeetCode Solution
I hope this Kth Smallest Element in a BST LeetCode Solution would be useful for you to learn something new from this problem. If it helped you then don’t forget to bookmark our site for more Coding Solutions.
This Problem is intended for audiences of all experiences who are interested in learning about Data Science in a business context; there are no prerequisites.
Keep Learning!
More Coding Solutions >>