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.

 

By Aditya Bhuyan

I work as a cloud specialist. In addition to being an architect and SRE specialist, I work as a cloud engineer and developer. I have assisted my clients in converting their antiquated programmes into contemporary microservices that operate on various cloud computing platforms such as AWS, GCP, Azure, or VMware Tanzu, as well as orchestration systems such as Docker Swarm or Kubernetes. For over twenty years, I have been employed in the IT sector as a Java developer, J2EE architect, scrum master, and instructor. I write about Cloud Native and Cloud often. Bangalore, India is where my family and I call home. I maintain my physical and mental fitness by doing a lot of yoga and meditation.

Leave a Reply

Your email address will not be published. Required fields are marked *

error

Enjoy this blog? Please spread the word :)