↓Skip to main content
  1. LeetCode/

LeetCode 230: Kth Smallest Element in a BST

·1 min· ·
LeetCode Medium Tree Depth-First-Search Binary-Search-Tree Binary-Tree
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: medium First Attempt: 2022-10-29

  • Submissions: Runtime Error → Wrong Answer ×2 → Accepted ×5 → Wrong Answer ×3 → Accepted ×2

Approach
#

An in-order traversal of a BST is ascending (Tree Template 3). Run an iterative in-order (as in LC 94), decrementing k on each pop; when it hits 0 that node is the answer, without walking the whole tree.

My Attempts
#

One version returned the node instead of its value; several later rewrites returned None.

Solution
#

class Solution:
    def kthSmallest(self, root: Optional[TreeNode], k: int) -> int:
        stack, cur = [], root
        while True:
            while cur:
                stack.append(cur)
                cur = cur.left
            cur = stack.pop()
            k -= 1
            if k == 0:
                return cur.val
            cur = cur.right

Complexity
#

Time O(h + k), space O(h).

Mistakes to Avoid
#

  • Return the value, not the node.

Interview Explanation
#

A BST’s in-order is ascending, so I walk it iteratively and return the k-th value. Time O(h + k).

Related

LeetCode 98: Validate Binary Search Tree
·2 mins
LeetCode Medium Tree Depth-First-Search Binary-Search-Tree Binary-Tree
LeetCode 98 note: every node has a valid range (low, high); going left the upper bound becomes the node and going right the lower bound does; comparing parent and child is not enough
LeetCode 235: Lowest Common Ancestor of a Binary Search Tree
·2 mins
LeetCode Medium Tree Depth-First-Search Binary-Search-Tree Binary-Tree
LeetCode 235 note: go left when both p and q are smaller, right when both are larger; otherwise (split, or one is the node itself) this node is the LCA
LeetCode 1448: Count Good Nodes in Binary Tree
·1 min
LeetCode Medium Tree Depth-First-Search Breadth-First-Search Binary-Tree
LeetCode 1448 note: pass the path maximum down during DFS; a node is good when its value is at least that maximum
LeetCode 199: Binary Tree Right Side View
·1 min
LeetCode Medium Tree Depth-First-Search Breadth-First-Search Binary-Tree
LeetCode 199 note: in a level-order traversal, each level’s rightmost node is what you see from the right
LeetCode 938: Range Sum of BST
·2 mins
LeetCode Easy Tree Depth-First-Search Binary-Search-Tree Binary-Tree
LeetCode 938 note: prune with the BST order, going only right below low and only left above high, adding nodes inside the range
LeetCode 606: Construct String from Binary Tree
·1 min
LeetCode Medium String Tree Depth-First-Search Binary-Tree
LeetCode 606 note: output in pre-order, keeping an empty () when only the left subtree is missing, and omitting the right parentheses when it is empty