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).