Dsa 8,9
Dsa 8,9
class Node:
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
def right_rotate(y):
x = y.left
T2 = x.right
x.right = y
y.left = T2
return x
def left_rotate(x):
y = x.right
T2 = y.left
y.left = x
x.right = T2
x.height = max(height(x.left), height(x.right)) + 1
return y
if root is None:
return Node(key)
else:
return root
balance = balance_factor(root)
return right_rotate(root)
return left_rotate(root)
root.left = left_rotate(root.left)
return right_rotate(root)
root.right = right_rotate(root.right)
return left_rotate(root)
return root
def inorder(root):
if root:
inorder(root.left)
inorder(root.right)
def print_tree(root, level=0, prefix="Root: "):
if root.left or root.right:
if root.left:
else:
if root.right:
else:
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):
print_tree(root)
print()
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: