0% found this document useful (0 votes)
6 views7 pages

Dsa 8,9

The document contains Python code for implementing an AVL Tree and an Optimal Binary Search Tree (BST). It includes functions for inserting nodes, performing rotations to maintain balance in the AVL Tree, and calculating the optimal structure of a BST based on given keys and their frequencies. The code also provides a user interface for inputting data and displaying the resulting tree structures.

Uploaded by

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

Dsa 8,9

The document contains Python code for implementing an AVL Tree and an Optimal Binary Search Tree (BST). It includes functions for inserting nodes, performing rotations to maintain balance in the AVL Tree, and calculating the optimal structure of a BST based on given keys and their frequencies. The code also provides a user interface for inputting data and displaying the resulting tree structures.

Uploaded by

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

Assignment No:

AVL BST code DSA:-

class Node:

def __init__(self, key):

self.left = None

self.right = None

self.value = key

self.height = 1

def height(node):

if node is None:

return 0

return node.height

def balance_factor(node):

if node is None:

return 0

return height(node.left) - height(node.right)

def right_rotate(y):

print(f"Right Rotate on {y.value}")

x = y.left

T2 = x.right

x.right = y

y.left = T2

y.height = max(height(y.left), height(y.right)) + 1

x.height = max(height(x.left), height(x.right)) + 1

return x

def left_rotate(x):

print(f"Left Rotate on {x.value}")

y = x.right

T2 = y.left

y.left = x

x.right = T2
x.height = max(height(x.left), height(x.right)) + 1

y.height = max(height(y.left), height(y.right)) + 1

return y

def insert(root, key):

if root is None:

return Node(key)

if key < root.value:

root.left = insert(root.left, key)

elif key > root.value:

root.right = insert(root.right, key)

else:

return root

root.height = 1 + max(height(root.left), height(root.right))

balance = balance_factor(root)

print(f"Node {root.value} balance factor: {balance}")

if balance > 1 and key < root.left.value:

return right_rotate(root)

if balance < -1 and key > root.right.value:

return left_rotate(root)

if balance > 1 and key > root.left.value:

root.left = left_rotate(root.left)

return right_rotate(root)

if balance < -1 and key < root.right.value:

root.right = right_rotate(root.right)

return left_rotate(root)

return root

def inorder(root):

if root:

inorder(root.left)

print(root.value, end=' ')

inorder(root.right)
def print_tree(root, level=0, prefix="Root: "):

if root is not None:

print(" " * (level * 4) + prefix + str(root.value))

if root.left or root.right:

if root.left:

print_tree(root.left, level + 1, "L--- ")

else:

print(" " * ((level + 1) * 4) + "L--- None")

if root.right:

print_tree(root.right, level + 1, "R--- ")

else:

print(" " * ((level + 1) * 4) + "R--- None")

def construct_avl():

root = None

n = int(input("Enter the number of nodes you want to insert in the AVL tree: "))

for i in range(n):

key = int(input(f"Enter value for node {i+1}: "))

root = insert(root, key)

print(f"\nTree structure after inserting {key}:")

print_tree(root)

print()

print("Final In-order traversal of the AVL tree:")

inorder(root)

print()

if __name__ == "__main__":

construct_avl()
output:
Assignment no:
def sum_freq(freq, i, j):
return sum(freq[i:j + 1])
def optimal_bst(keys, freq, n):
cost = [[0 for _ in range(n)] for _ in range(n)]
root = [[0 for _ in range(n)] for _ in range(n)]
weight = [[0 for _ in range(n)] for _ in range(n)]
# Initialize the cost and weight matrices
for i in range(n):
cost[i][i] = freq[i]
root[i][i] = i
weight[i][i] = freq[i]
# Fill in the weight matrix
for length in range(2, n + 1): # length of the subarray
for i in range(n - length + 1):
j = i + length - 1
weight[i][j] = weight[i][j - 1] + freq[j]
# Compute the cost and root matrices
for L in range(2, n + 1): # length of subarrays
for i in range(n - L + 1):
j=i+L-1
cost[i][j] = float('inf')
for r in range(i, j + 1): # root from i to j
left_cost = cost[i][r - 1] if r > i else 0
right_cost = cost[r + 1][j] if r < j else 0
total_cost = left_cost + right_cost + weight[i][j]
if total_cost < cost[i][j]:
cost[i][j] = total_cost
root[i][j] = r
return cost, root, weight
def print_optimal_bst(root, i, j):
if i > j:
return None
r = root[i][j]
print(f"Root: {r} ({keys[r]})")
print_optimal_bst(root, i, r - 1)
print_optimal_bst(root, r + 1, j)
if __name__ == "__main__":
try:
n = int(input("Enter number of keys: "))
keys = list(map(int, input("Enter the keys: ").split()))
freq = list(map(int, input("Enter the frequencies: ").split()))
if len(keys) != n or len(freq) != n:
raise ValueError("Number of keys and frequencies must match.")
cost, root, weight = optimal_bst(keys, freq, n)
print(f"Optimal BST Cost: {cost[0][n - 1]}")
print("Root Matrix:")
for row in root:
print(row)
print("Weight Matrix:")
for row in weight:
print(row)
print("\nOptimal BST Structure:")
print_optimal_bst(root, 0, n - 1)
except ValueError as e:
print(f"Error: {e}")

Output:

You might also like