बाइनरी सर्च ट्री में एक नोड इनसर्ट करना
वीडियो में, आपने सीखा कि बाइनरी सर्च ट्री (BST) क्या होते हैं और उनकी मुख्य ऑपरेशन्स को कैसे इम्प्लीमेंट किया जाता है।
इस अभ्यास में, आप BST में एक नोड इनसर्ट करने के लिए एक फंक्शन इम्प्लीमेंट करेंगे।
अपने कोड को टेस्ट करने के लिए, आप निम्न ट्री का उपयोग कर सकते हैं:

नोड्स में किताबों के टाइटल हैं, जो अल्फ़ाबेटिकल ऑर्डर के आधार पर एक BST बनाते हैं।
यह ट्री bst वैरिएबल में प्रीलोड किया गया है:
bst = CreateTree()
आप इस कोड से जाँच सकते हैं कि नोड सही ढंग से इनसर्ट हुआ है या नहीं:
bst.insert("Pride and Prejudice")
print(search(bst, "Pride and Prejudice"))
यह अभ्यास पाठ्यक्रम का हिस्सा है
Python में Data Structures और Algorithms
अभ्यास निर्देश
- जाँच करें कि BST खाली है या नहीं।
- जाँच करें कि जो डेटा इनसर्ट करना है, वह करंट नोड के डेटा से छोटा है या नहीं।
- जाँच करें कि जो डेटा इनसर्ट करना है, वह करंट नोड के डेटा से बड़ा है या नहीं।
इंटरैक्टिव व्यावहारिक अभ्यास
इस अभ्यास को इस नमूना कोड को पूरा करके आज़माएँ।
class BinarySearchTree:
def __init__(self):
self.root = None
def insert(self, data):
new_node = TreeNode(data)
# Check if the BST is empty
if ____ == None:
self.root = new_node
return
else:
current_node = self.root
while True:
# Check if the data to insert is smaller than the current node's data
if ____ < ____:
if current_node.left_child == None:
current_node.left_child = new_node
return
else:
current_node = current_node.left_child
# Check if the data to insert is greater than the current node's data
elif ____ > ____:
if current_node.right_child == None:
current_node.right_child = new_node
return
else:
current_node = current_node.right_child
bst = CreateTree()
bst.insert("Pride and Prejudice")
print(search(bst, "Pride and Prejudice"))