You are on page 1of 2

Lloyd Trista M.

Dagoc

2F5

Data Structure with Algorithm

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:

def __init__(self, key):

self.key = key

self.left = None

self.right = None

# Algorithm to insert a key into a binary tree

def insert(root, key):

if root is None:

return TreeNode(key)

else:

if key < root.key:

root.left = insert(root.left, key)

else:

root.right = insert(root.right, key)

return root

# Algorithm to perform an in-order traversal of a binary tree

def inorder_traversal(root):

if root:

inorder_traversal(root.left)
print(root.key, end=' ')

inorder_traversal(root.right)

# Example usage:

# Constructing a binary tree

root = None

keys = [5, 3, 7, 2, 4, 6, 8]

for key in keys:

root = insert(root, key)

# Performing in-order traversal

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.

You might also like