题目链接:230.二叉搜索树的第K小的元素
两个做法:一个是递归,一个是迭代;
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def kthSmallest(self, root: TreeNode, k: int) -> int:
if not root:
return []
#迭代
stack,res = [],[]
cur = root
i=1
while stack or cur:
while cur:
stack.append(cur)
cur = cur.left
cur = stack.pop()
if k==i:
return cur.val
cur = cur.right
i+=1
#递归
res = []
def helper(root):
if not root:
return
helper(root.left)
res.append(root.val)
helper(root.right)
helper(root)
return res[k-1]