Insert into a Binary Search Tree
LeetCode 701 · মাঝারি · সমাধান, intuition ও ধাপে ধাপে ওয়াকথ্রু
Search for the value; attach at the first empty slot.
আমি 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
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.
আমি কীভাবে সমাধান করেছি
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 rootInsert 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).