二叉搜索树中第K小的元素
230.二叉搜索树中第K小的元素
题目描述
思路:中序遍历
根据二叉搜索树的性质,中序遍历按照访问左子树-根结点-右子树的方式遍历二叉树,在遍历过程中很容就能找到第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: Optional[TreeNode], k: int) -> int:
ans = []
while root or ans:
while root:
ans.append(root)
root = root.left
root = ans.pop()
k -= 1
if k == 0:
return root.val
root = root.right