BST Prog.
BST Prog.
Here’s a simple Python program to construct a Binary Search Tree (BST) using classes and
objects, focusing on keeping the inner workings straigh orward:
class Node:
self.key = key
self.le = None
self.right = None
class BST:
def __init__(self):
self.root = None
if self.root is None:
self.root = Node(key)
else:
self._insert(self.root, key)
if current_node.le is None:
current_node.le = Node(key)
else:
self._insert(current_node.le , key)
# If the new key is greater than or equal to the current node's key, go right
else:
if current_node.right is None:
current_node.right = Node(key)
else:
self._insert(current_node.right, key)
def in_order_traversal(self):
result = []
self._in_order_traversal(self.root, result)
return result
if node:
self._in_order_traversal(node.le , result)
result.append(node.key)
self._in_order_traversal(node.right, result)
def pre_order_traversal(self):
result = []
self._pre_order_traversal(self.root, result)
return result
if node:
result.append(node.key)
# Traverse the le subtree
self._pre_order_traversal(node.le , result)
self._pre_order_traversal(node.right, result)
def post_order_traversal(self):
result = []
self._post_order_traversal(self.root, result)
return result
if node:
self._post_order_traversal(node.le , result)
self._post_order_traversal(node.right, result)
result.append(node.key)
# Example usage
bst = BST()
bst.insert(num)
Explana on:
o __init__(self, key): Ini alizes a node with a key and le /right pointers set to None.
o insert(self, key): Inserts a key into the BST. Calls _insert() to handle the actual
inser on logic.
Traversal Outputs:
Pre-order Traversal: Visits nodes star ng from the root, then le subtree, followed by right
subtree.
Post-order Traversal: Visits nodes star ng from the le subtree, then right subtree, followed
by the root.
This program constructs a BST from the given set of numbers and performs different traversals to
display the order of nodes. If you have any more ques ons or need further details, feel free to ask!