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