In the below example:

  • The TreeNode class is defined with an __init__ method to initialize each node with a key and set its left and right children to None.
  • Nodes are created and connected to form a binary tree.
  • The in_order_traversal function performs an in-order traversal of the tree, printing the keys of the nodes in sorted order.
  • You can extend this basic structure to implement more complex tree structures, such as binary search trees, n-ary trees, or other specialized tree types based on your requirements.
  • If you have specific requirements for the tree structure or functionality, feel free to provide more details, and I can help you tailor the implementation accordingly.
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

Explanation:

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.

Need Help With Python Development?

Work with our skilled Python developers to accelerate your project and boost its performance.

Hire Python Developers

Support On Demand!

Related Q&A