Manipulate trees using level-order (breadth-first) indexing
mainBinarytree supports level-order indexing, allowing you to access, replace, or delete nodes using their position in a breadth-first traversal. This is similar to how binary heaps are represented in arrays.
- Access: Use
root[index]to get the node at that index. - Replace: Use
root[index] = new_nodeto replace a subtree. - Delete: Use
del root[index]to remove a subtree. - Visualization: Use
root.pprint(index=True)to print the tree with both node values and their level-order indices.
from binarytree import Node
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.right = Node(4)
root.left.right.left = Node(5)
# View indices
root.pprint(index=True)
# Access node at index 9
node_9 = root[9]
# Replace node at index 4
root[4] = Node(6, left=Node(7), right=Node(8))
# Delete node at index 1
del root[1]