Python Program for Tree Traversals
This program demonstrates three types of binary tree traversals: in-order, pre-order, and post-order. These traversal methods are implemented recursively to visit each node in the specific order required by each traversal type.
class TreeNode:
"""A node in a binary tree."""
def __init__(self, value):
"""
Initialize a tree node with a value.
:param value: int, the integer value of the node
"""
self.val = value
self.left = None
self.right = None
def inorderTraversal(root):
"""
Perform in-order traversal of the binary tree.
:param root: TreeNode, the root of the binary tree
:return: List[int], the elements in in-order
"""
if root is None:
return []
return inorderTraversal(root.left) + [root.val] + inorderTraversal(root.right)
def preorderTraversal(root):
"""
Perform pre-order traversal of the binary tree.
:param root: TreeNode, the root of the binary tree
:return: List[int], the elements in pre-order
"""
if root is None:
return []
return [root.val] + preorderTraversal(root.left) + preorderTraversal(root.right)
def postorderTraversal(root):
"""
Perform post-order traversal of the binary tree.
:param root: TreeNode, the root of the binary tree
:return: List[int], the elements in post-order
"""
if root is None:
return []
return postorderTraversal(root.left) + postorderTraversal(root.right) + [root.val]
# Example Usage
if __name__ == "__main__":
# Construct a simple binary tree
root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(3)
root.left.left = TreeNode(4)
root.left.right = TreeNode(5)
# In-order traversal
print("In-order traversal:", inorderTraversal(root))
# Pre-order traversal
print("Pre-order traversal:", preorderTraversal(root))
# Post-order traversal
print("Post-order traversal:", postorderTraversal(root))
The program defines a TreeNode
class to represent the nodes of the tree and three functions to perform each type of traversal. Each traversal function recursively visits nodes according to the traversal order: in-order, pre-order, or post-order. The results are returned as lists of values, demonstrating the order in which nodes are visited.