Tensorum
YouTubeనేర్చుకోవడం ప్రారంభించండి
LeetCode 230 · BST

Kth Smallest Element in a BST

LeetCode 230 · మధ్యస్థం · పరిష్కారం, intuition & దశలవారీ వాక్‌త్రూ

In-order traversal → index k−1.

మధ్యస్థంTreeDepth-First SearchBinary Search TreeBinary Tree
LeetCode లో తెరవండి ↗

నేను Kth Smallest Element in a BST (LeetCode 230) ను ఇలా పరిష్కరించాను — BST ప్యాటర్న్‌లోని ఒక మధ్యస్థం ప్రాబ్లమ్. కింద: intuition, దశలవారీ approach, నా accepted Python కోడ్, animated test cases, line-by-line debugger.

కింది వివరణ ఇంగ్లీష్‌లో ఉంది.

Intuition

An in-order traversal of a BST lists values in sorted order, so the kth value visited is the kth smallest.

Approach

  1. 1

    In-order DFS into a list.

  2. 2

    Return arr[k − 1].

నేను ఎలా పరిష్కరించాను

In-order listPythonO(n) time · O(n) space
class Solution:
    def kthSmallest(self, root, k):
        arr = []

        def dfs(node):
            if node is None:
                return
            dfs(node.left)
            arr.append(node.val)
            dfs(node.right)
        dfs(root)
        return arr[k - 1]
స్టెప్-త్రూ లోడ్ అవుతోంది…

Kth Smallest Element in a BST — తరచూ అడిగే ప్రశ్నలు

Kth Smallest Element in a BST వెనుక ఉన్న intuition ఏమిటి?

An in-order traversal of a BST lists values in sorted order, so the kth value visited is the kth smallest.

Kth Smallest Element in a BST (LeetCode 230) ను ఎలా పరిష్కరించాలి?

1. In-order DFS into a list. 2. Return arr[k − 1].

Kth Smallest Element in a BST యొక్క time, space complexity ఎంత?

Time: O(n). Space: O(n). (Accepted approach: In-order list.)

Kth Smallest Element in a BST లో సాధారణ పొరపాట్లు ఏమిటి?

Stopping the traversal after k nodes makes it O(h + k).