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