class TreeNode:
def __init__(self, key):
self.key = key
self.left = None
self.right = None
# Example Usage
# Creating nodes
root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(3)
root.left.left = TreeNode(4)
root.left.right = TreeNode(5)
# Traversing the tree (In-order traversal)
def in_order_traversal(node):
if node:
in_order_traversal(node.left)
print(node.key, end=" ")
in_order_traversal(node.right)
print("In-order traversal:")
in_order_traversal(root)
Here’s the textual representation of the binary tree created by the code:
1 / \ 2 3 / \ 4 5
The root of the tree is the node with the key 1.
The left child of 1 is the node with the key 2, and the right child is the node with the key 3.
The left child of 2 is the node with the key 4, and the right child is the node with the key 5.
Work with our skilled Python developers to accelerate your project and boost its performance.
Hire Python Developers