230. Kth Smallest Element in a BST

230. Kth Smallest Element in a BSTarrow-up-right

中序遍歷

中序遍歷的順序,就是 BST 的大小順序

class Solution:
    def __init__(self):
        self.rank = 0
    def kthSmallest(self, root: Optional[TreeNode], k: int) -> int:

        ans = root.val
        def inorder(root):
            nonlocal ans
            if not root:
                return
            inorder(root.left)
            self.rank += 1
            if self.rank == k:
                ans = root.val
            inorder(root.right)

        inorder(root)
        return ans

迭代(中序遍歷)

Last updated