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