Tensorum
YouTubeகற்கத் தொடங்குங்கள்
LeetCode 1008 · Construction / Serialization

Construct Binary Search Tree from Preorder Traversal

LeetCode 1008 · நடுத்தரம் · தீர்வு, intuition & படிப்படியான வாக்த்ரூ

Pre-order index + upper bound recursion.

நடுத்தரம்ArrayStackTreeBinary Search TreeMonotonic Stack
LeetCode இல் திற ↗

நான் Construct Binary Search Tree from Preorder Traversal (LeetCode 1008) ஐ இப்படித் தீர்த்தேன் — Construction / Serialization பேட்டர்னின் ஒரு நடுத்தரம் பிராப்ளம். கீழே: intuition, படிப்படியான approach, என் accepted Python கோட், animated test cases மற்றும் line-by-line debugger.

கீழேயுள்ள விளக்கம் ஆங்கிலத்தில் உள்ளது.

Intuition

Consume the pre-order list left to right. Each value becomes a node, its left subtree takes the following values smaller than it, and its right subtree takes values up to the ancestor's bound.

Approach

  1. 1

    dfs(bound): stop if the list is used up or the next value exceeds bound.

  2. 2

    Create a node and advance the index.

  3. 3

    left = dfs(node.val); right = dfs(bound).

நான் எப்படித் தீர்த்தேன்

Bounded pre-order recursionPythonO(n) time
class Solution:
    def bstFromPreorder(self, preorder):
        self.i = 0

        def dfs(preorder, upperBound):
            if self.i == len(preorder) or preorder[self.i] > upperBound:
                return None
            root = TreeNode(preorder[self.i])
            self.i += 1
            root.left = dfs(preorder, root.val)
            root.right = dfs(preorder, upperBound)
            return root
        return dfs(preorder, float("inf"))
ஸ்டெப்-த்ரூ ஏற்றுகிறது…

Construct Binary Search Tree from Preorder Traversal — அடிக்கடி கேட்கப்படும் கேள்விகள்

Construct Binary Search Tree from Preorder Traversal பின்னாலுள்ள intuition என்ன?

Consume the pre-order list left to right. Each value becomes a node, its left subtree takes the following values smaller than it, and its right subtree takes values up to the ancestor's bound.

Construct Binary Search Tree from Preorder Traversal (LeetCode 1008) ஐ எப்படித் தீர்ப்பது?

1. dfs(bound): stop if the list is used up or the next value exceeds bound. 2. Create a node and advance the index. 3. left = dfs(node.val); right = dfs(bound).

Construct Binary Search Tree from Preorder Traversal இன் time மற்றும் space complexity என்ன?

Time: O(n). Space: O(h). (Accepted approach: Bounded pre-order recursion.)

Construct Binary Search Tree from Preorder Traversal இல் பொதுவான தவறுகள் என்ன?

Inserting values one by one is O(n²) for sorted input.