Kth Smallest Element in a BST LeetCode solution in Python
1# Runtime: 86 ms (Top 42.71%) | Memory: 18.1 MB (Top 15.27%)234# Definition for a binary tree node.5# class TreeNode:6# def __init__(self, val=0, left=None, right=None):7# self.val = val8# self.left = left9# self.right = right10class Solution:11def kthSmallest(self, root: Optional[TreeNode], k: int) -> int:12n = 013stack = [] # to store the elements14cur = root # pointer to iterate15while cur or stack:16while cur: # used to find the left most element17stack.append(cur)18cur = cur.left19cur = (20stack.pop()21) # pop the most recent element which will be the least value at that moment22n += 123if n == k:24return cur.val25cur = cur.right