class Node:
def __init__(self, key):
self.left = None
self.right = None
self.val = key
class BST:
def __init__(self):
self.root = None
def insert(self, root, key):
if root is None:
return Node(key)
if key < root.val:
root.left = self.insert(root.left, key)
else:
root.right = self.insert(root.right, key)
return root
def inorder(self, root):
if root:
self.inorder(root.left)
print(root.val, end=" ")
self.inorder(root.right)
I have a few questions:
1.Is this the best approach for insertion in a BST, or can it be optimized?
2.How can I make the in-order traversal more Python or efficient?
3.What would be a good way to handle edge cases, like inserting duplicate elements or balancing the tree?
I’m trying to implement a binary search tree (BST) in Python, but I’m facing some issues with the insertion and traversal processes.
Specifically, I’m not sure if my approach is optimal, and I’m struggling with writing clean code for in order traversal.
user26858167 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.