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

Binary Search Tree and Postfix Evaluation

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)
40 views4 pages

Binary Search Tree and Postfix Evaluation

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

class TreeNode:

def __init__(self, key):

[Link] = None

[Link] = None

[Link] = key

def count_less_than(root, key):

if root is None:

return 0

if [Link] < key:

return 1 + count_less_than([Link], key) + count_less_than([Link], key)

else:

return count_less_than([Link], key)

q2

class BinarySearchTree:

def __init__(self):

[Link] = None

class Node:

def __init__(self, key):

[Link] = None

[Link] = None

[Link] = key
def insert(self, key):

if [Link] is None:

[Link] = [Link](key)

else:

self._insert([Link], key)

def _insert(self, node, key):

if key < [Link]:

if [Link] is None:

[Link] = [Link](key)

else:

self._insert([Link], key)

else:

if [Link] is None:

[Link] = [Link](key)

else:

self._insert([Link], key)

def search(self, key):

return self._search([Link], key)

def _search(self, node, key):

if node is None or [Link] == key:

return node
if key < [Link]:

return self._search([Link], key)

return self._search([Link], key)

q3

def evaluate_postfix(expression):

stack = []

for token in [Link]():

if [Link]():

[Link](int(token))

else:

b = [Link]()

a = [Link]()

if token == '+':

[Link](a + b)

elif token == '-':

[Link](a - b)

elif token == '*':

[Link](a * b)

elif token == '/':

[Link](a / b)

return [Link]()

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

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


print(":", result)

You might also like