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

Insert into a Binary Search Tree

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

Search for the value; attach at the first empty slot.

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

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

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

Intuition

Walk down like a search: smaller values go left, larger go right. When the direction you need has no child, that empty spot is where the new value belongs.

Approach

  1. 1

    Empty tree → new node.

  2. 2

    Recurse into the side the value belongs to.

  3. 3

    If that side is empty at this node, attach the new node there.

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

Recursive descentPythonO(h) time
class Solution:
    def insertIntoBST(self, root, val):
        if root is None:
            return TreeNode(val)
        if root is not None and val > root.val:
            self.insertIntoBST(root.right, val)
        elif root is not None and val < root.val:
            self.insertIntoBST(root.left, val)
        if root is not None and val < root.val and root.left is None:
            root.left = TreeNode(val)
        elif root is not None and val > root.val and root.right is None:
            root.right = TreeNode(val)
        return root
స్టెప్-త్రూ లోడ్ అవుతోంది…

Insert into a Binary Search Tree — తరచూ అడిగే ప్రశ్నలు

Insert into a Binary Search Tree వెనుక ఉన్న intuition ఏమిటి?

Walk down like a search: smaller values go left, larger go right. When the direction you need has no child, that empty spot is where the new value belongs.

Insert into a Binary Search Tree (LeetCode 701) ను ఎలా పరిష్కరించాలి?

1. Empty tree → new node. 2. Recurse into the side the value belongs to. 3. If that side is empty at this node, attach the new node there.

Insert into a Binary Search Tree యొక్క time, space complexity ఎంత?

Time: O(h). Space: O(h). (Accepted approach: Recursive descent.)

Insert into a Binary Search Tree లో సాధారణ పొరపాట్లు ఏమిటి?

The cleaner form is root.left = insert(root.left, val).