Professional Documents
Culture Documents
DSA Lloyd Dagoc
DSA Lloyd Dagoc
Dagoc
2F5
A binary tree is a tree data structure in which each node has at most two children, referred to as the
left child and the right child.
python
Copy code
class TreeNode:
self.key = key
self.left = None
self.right = None
if root is None:
return TreeNode(key)
else:
else:
return root
def inorder_traversal(root):
if root:
inorder_traversal(root.left)
print(root.key, end=' ')
inorder_traversal(root.right)
# Example usage:
root = None
keys = [5, 3, 7, 2, 4, 6, 8]
print("In-order traversal:")
inorder_traversal(root)
In this example, the TreeNode class represents a node in the binary tree, and the insert function is used
to insert a key into the binary tree. The inorder_traversal function performs an in-order traversal of the
binary tree, printing the keys in sorted order.