#1 India's Top IT Training Institute

×

About Uncodemy

Know more about who we are and what we stand for.

About Us

About Us

Discover our mission to equip individuals with essential IT skills and industry expertise.

Read More →
UnCodeMy Gallery

UnCodeMy Gallery

Explore highlights from our IT training sessions and success stories.

Read More →
×

Free Resources

Learn, practice and plan your career — bilkul free.

Tutorials

Tutorials

Step-by-step written tutorials to learn any technology at your own pace.

Read More →
Free Counselling

Free Counselling

Book a free video counselling session and pick the right course for you.

Read More →
Online Compiler

Online Compiler

Write, run and test your code online — no setup required.

Read More →
Trees

Binary Tree Traversal in Data Structure

Traversal refers to visiting every node of a binary tree exactly once in a specific order. There are four common traversal techniques: Inorder, Preorder, Postorder, and Level Order.

Inorder Traversal (Left, Root, Right)

Visits the left subtree, then the root, then the right subtree. For a Binary Search Tree, inorder traversal produces values in sorted order.

def inorder(node, result=None):
    if result is None:
        result = []
    if node:
        inorder(node.left, result)
        result.append(node.val)
        inorder(node.right, result)
    return result

Preorder Traversal (Root, Left, Right)

Visits the root first, then the left subtree, then the right subtree. Useful for creating a copy of the tree.

def preorder(node, result=None):
    if result is None:
        result = []
    if node:
        result.append(node.val)
        preorder(node.left, result)
        preorder(node.right, result)
    return result

Postorder Traversal (Left, Right, Root)

Visits the left subtree, then the right subtree, then the root. Useful for deleting a tree or evaluating expression trees.

def postorder(node, result=None):
    if result is None:
        result = []
    if node:
        postorder(node.left, result)
        postorder(node.right, result)
        result.append(node.val)
    return result

Level Order Traversal (Breadth First)

Visits nodes level by level, using a queue.

from collections import deque

def level_order(root):
    if not root:
        return []
    result, queue = [], deque([root])
    while queue:
        node = queue.popleft()
        result.append(node.val)
        if node.left: queue.append(node.left)
        if node.right: queue.append(node.right)
    return result

Complexity

TraversalTimeSpace
All four traversalsO(n)O(h) for recursive, O(n) for level order

Ready to master Data Structures & Algorithms?

Learn DSA hands-on with mentor-led sessions, real interview practice, and placement support.

Explore Course