Check if the BST is empty. Check if the data to insert is smaller than the current node's data. Check if the data to ins

动态 未结 0 66
小小草
小小草 LV1 2023年9月23日 23:40 发表
Here's the completed code: ``` class BinarySearchTree: def __init__(self): self.root = None def insert(self, data): new_node = TreeNode(data) # Check if the BST is empty if self.root == 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 data < current_node.data: 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 data > current_node.data: if current_node.right_child == None: current_node.right_child = new_node return else: current_node = current_node.right_child bst = BinarySearchTree() bst.insert("Pride and Prejudice") print(search(bst, "Pride and Prejudice")) ``` The code defines a BinarySearchTree class with an insert method that inserts a new node into the tree. It starts by creating a new node with the given data. Then, it checks whether the root of the tree is None, which means that the tree is empty. If it is, it sets the root to the new node and returns. Otherwise, it sets the current node to the root and enters a loop that continues until it finds a suitable place to insert the new node. In each iteration, it checks whether the data to insert is smaller than the current node's data. If it is, it checks whether the current node has a left child. If it doesn't, it sets the left child to the new node and returns. If it does, it sets the current node to the left child and continues the loop. If the data to insert is greater than the current node's data, it checks whether the current node has a right child. If it doesn't, it sets the right child to the new node and returns. If it does, it sets the current node to the right child and continues the loop. Finally, it creates a BinarySearchTree object, inserts a node with the data "Pride and Prejudice", and then calls the search function to check whether the node was inserted correctly.
收藏(0)  分享
相关标签: 智能问答
问题没解决?让AI助手帮你作答 AI助手
0个回复
  • 消灭零回复