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

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