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.