Relative Content

Tag Archive for pythonalgorithmdata-structuresbinary-search-tree

Why does my Binary Search Tree implementation fail to handle duplicate values correctly?

I’m working on implementing a Binary Search Tree (BST) in Python and I’m running into an issue when the tree encounters duplicate values. I understand that traditionally, a BST doesn’t handle duplicates, but I want to modify my tree to allow duplicate values either by storing them in the left subtree, right subtree, or using some other strategy.

How to efficiently implement and traverse a binary search tree (BST) in Python?

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=” “) […]