A binary tree is a hierarchical data structure in which each node has at most two children, referred to as the left child and the right child. Binary trees are widely used in various applications such as expression parsing, searching, and sorting algorithms.
Consider a binary tree with the following structure:
1
/ \
2 3
/ \
4 5
In this binary tree, the root node is 1, which has two children 2 and 3. Node 2 has two children 4 and 5, while node 3 has no children.
Binary trees have several important properties:
class Node:
def __init__(self, key):
self.left = None
self.right = None
self.val = key
class BinaryTree:
def __init__(self):
self.root = None
def insert(self, key):
if self.root is None:
self.root = Node(key)
else:
self._insert(self.root, key)
def _insert(self, current, key):
if key < current.val:
if current.left is None:
current.left = Node(key)
else:
self._insert(current.left, key)
else:
if current.right is None:
current.right = Node(key)
else:
self._insert(current.right, key)
def inorder_traversal(self, root):
if root:
self.inorder_traversal(root.left)
print(root.val, end=' ')
self.inorder_traversal(root.right)
# Example usage:
bt = BinaryTree()
bt.insert(1)
bt.insert(2)
bt.insert(3)
bt.insert(4)
bt.insert(5)
bt.inorder_traversal(bt.root) # Output: 1 2 3 4 5
This code defines a simple binary tree with methods for inserting nodes and performing in-order traversal.
There are several types of binary trees, each with distinct characteristics:
Binary trees are a fundamental data structure that provides efficient hierarchical data management. Understanding their components, properties, and types is crucial for implementing various algorithms and solving complex problems.