AVL Tree With Comments
AVL Tree With Comments
class AVLNode:
class AVLTree:
def __init__(self):
# Base case: if the node is None, create a new node with the given key
if not node:
return AVLNode(key)
# If the key to insert is less than the current node's key, go to the left subtree
# If the key to insert is greater than the current node's key, go to the right subtree
else:
return node
# Update the height of the current node based on the heights of its children
balance = self._get_balance(node)
return self._rotate_right(node)
node.left = self._rotate_left(node.left)
return self._rotate_right(node)
return self._rotate_left(node)
node.right = self._rotate_right(node.right)
return self._rotate_left(node)
# Return the (potentially new) root of this subtree
return node
if not node:
return node
# If the key to delete is less than the current node's key, go to the left subtree
# If the key to delete is greater than the current node's key, go to the right subtree
# If the key is equal to the current node's key, this is the node to delete
else:
if not node.left:
return node.right
if not node.right:
return node.left
# Case 2: Node has two children, get the in-order successor (smallest in the right subtree)
temp = self._get_min_value_node(node.right)
if not node:
return node
balance = self._get_balance(node)
return self._rotate_right(node)
node.left = self._rotate_left(node.left)
return self._rotate_right(node)
return self._rotate_left(node)
# Case 4: Right Left Case (right-left rotation needed)
node.right = self._rotate_right(node.right)
return self._rotate_left(node)
return node
T2 = y.left # 'T2' is the left subtree of 'y' that becomes the right subtree of 'z'
# Perform rotation
y.left = z
z.right = T2
return y
T3 = y.right # 'T3' is the right subtree of 'y' that becomes the left subtree of 'z'
# Perform rotation
y.right = z
z.left = T3
return y
if not node:
if not node:
return self._get_min_value_node(node.left)
# Method to perform in-order traversal of the tree and collect keys in a list
if node:
def read_elements_from_file(filename):
try:
except FileNotFoundError:
return []
except ValueError as e:
return []
def main():
input_filename = 'input.txt'
output_filename = 'output.txt'
elements = read_elements_from_file(input_filename)
if not elements:
return
avl_tree = AVLTree()
avl_tree.insert(element)
avl_tree.insert(15)
avl_tree.delete(20)
result = []
avl_tree.in_order_traversal(avl_tree.root, result)
if __name__ == '__main__':
main()
output = file.read()
OUTPUT :-
Output content: 5 10 15 25 30 40 50