BST中第K小的元素
https://www.lintcode.com/problem/902/?utm_source=sc-cheatsheet-cyc
输入:{1,#,2},2输出:2解释: 1 \ 2第二小的元素是2。输入:{2,1,3},1输出:1解释: 2 / \1 3第一小的元素是1。解题思路
```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
```Last updated