```python
from lintcode import (
TreeNode,
)
"""
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
class Solution:
"""
@param root: the given BST
@param k: the given k
@return: the kth smallest element in BST
"""
def kth_smallest(self, root: TreeNode, k: int) -> int:
# write your code here
if not root:
return None
s = []
cur = root
res = None
while k > 0 and (s or cur): #s or cur, 是因为stack存左树,cur存右树。所有左右树都没有的情况都要考虑
while cur:
s.append(cur)
cur = cur.left
cur = s.pop()
k -= 1
res = cur.val
cur = cur.right
return res
```