0% found this document useful (0 votes)
11 views4 pages

HM 2

The document contains Python code for implementing a binary search tree (BST) with methods for inserting and searching nodes, as well as a function to count nodes with values less than a given key. Additionally, it includes a function to evaluate postfix expressions using a stack. An example of using the postfix evaluation function is also provided.

Uploaded by

prbzd2rddh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as RTF, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views4 pages

HM 2

The document contains Python code for implementing a binary search tree (BST) with methods for inserting and searching nodes, as well as a function to count nodes with values less than a given key. Additionally, it includes a function to evaluate postfix expressions using a stack. An example of using the postfix evaluation function is also provided.

Uploaded by

prbzd2rddh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as RTF, PDF, TXT or read online on Scribd
You are on page 1/ 4

class TreeNode:

def __init__(self, key):

self.left = None

self.right = None

self.val = key

def count_less_than(root, key):

if root is None:

return 0

if root.val < key:

return 1 + count_less_than(root.left, key) + count_less_than(root.right, key)

else:

return count_less_than(root.left, key)

q2

class BinarySearchTree:

def __init__(self):

self.root = None

class Node:

def __init__(self, key):

self.left = None

self.right = None

self.val = key
def insert(self, key):

if self.root is None:

self.root = self.Node(key)

else:

self._insert(self.root, key)

def _insert(self, node, key):

if key < node.val:

if node.left is None:

node.left = self.Node(key)

else:

self._insert(node.left, key)

else:

if node.right is None:

node.right = self.Node(key)

else:

self._insert(node.right, key)

def search(self, key):

return self._search(self.root, key)

def _search(self, node, key):

if node is None or node.val == key:

return node
if key < node.val:

return self._search(node.left, key)

return self._search(node.right, key)

q3

def evaluate_postfix(expression):

stack = []

for token in expression.split():

if token.isdigit():

stack.append(int(token))

else:

b = stack.pop()

a = stack.pop()

if token == '+':

stack.append(a + b)

elif token == '-':

stack.append(a - b)

elif token == '*':

stack.append(a * b)

elif token == '/':

stack.append(a / b)

return stack.pop()

# ‫مثال لالستخدام‬

result = evaluate_postfix("5 6 2 + *")


print(":", result)

You might also like