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.