This is the code I came up with to insert a new value into a BST:
class BST(object):
def __init__(self, root):
self.root = Node(root)
def insert(self, new_val):
self.__internal_insert(self.root, new_val)
def __internal_insert(self, node, new_val):
if node is None:
node = Node(new_val)
elif new_val < node.value:
self.__internal_insert(node.left, new_val)
else:
self.__internal_insert(node.right, new_val)
# Set up the tree
tree = BST(4)
# Insert elements
tree.insert(2)
tree.insert(1)
tree.insert(3)
tree.insert(5)
however, while debugging I noticed that the self.root
is never updated, eg.: as soon as the __internal_insert()
method finishes and a new insert()
is performed, its sibling nodes left
and right
are back to None
instead to the previous value that was set.
Hope you help me spot where the bug is. I picked up Python recently, my apologizes if this is a trivial question.
You defined node = Node(new_val)
, but then where do you ever attach that node to it's parent?
Basically, you recurse, but never captured the results you're building
Try returning the node you created
def __internal_insert(self, node, new_val):
if node is None:
node = Node(new_val)
elif new_val < node.value:
node.left = self.__internal_insert(node.left, new_val)
else:
node.right = self.__internal_insert(node.right, new_val)
return node
I see two issues with the code.
First, when you reassign node
, it is not assigning the value to the BST
object. To do that, you need to reference it directly: self.left = Node(new_val)
.
Second, you're not checking the equals condition, so your code isn't going to work like a traditional BST. You'll end up with a lot of extraneous nodes.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.