Binary Trees
In computer science, a binary tree is a type of tree data structure in which each node has at most two children, referred to as left
child and right
child. The left child node is smaller than its parent, while the right child node is larger.
Binary trees have numerous applications in computer science and are commonly used in various algorithms and data structures. They are particularly useful for representing hierarchical data and performing efficient searches.
Here's an example of creating and traversing a binary tree using Python:
1if __name__ == '__main__':
2 class Node:
3 def __init__(self, data):
4 self.data = data
5 self.left = None
6 self.right = None
7
8 # Create a binary tree
9 root = Node(1)
10 root.left = Node(2)
11 root.right = Node(3)
12 root.left.left = Node(4)
13 root.left.right = Node(5)
14
15 # Print the values of the binary tree
16 def in_order_traversal(node):
17 if node:
18 in_order_traversal(node.left)
19 print(node.data, end=' ')
20 in_order_traversal(node.right)
21
22 print('In-order Traversal: ', end='')
23 in_order_traversal(root)
In this example, we create a binary tree with nodes labeled from 1 to 5. We then perform an in-order traversal, which visits each node of the tree in an order: left subtree, current node, right subtree.
The output of the code will be:
1In-order Traversal: 4 2 5 1 3
xxxxxxxxxx
if __name__ == '__main__':
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
# Create a binary tree
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
# Print the values of the binary tree
def in_order_traversal(node):
if node:
in_order_traversal(node.left)
print(node.data, end=' ')
in_order_traversal(node.right)
print('In-order Traversal: ', end='')
in_order_traversal(root)