Use app×
QUIZARD
QUIZARD
JEE MAIN 2026 Crash Course
NEET 2026 Crash Course
CLASS 12 FOUNDATION COURSE
CLASS 10 FOUNDATION COURSE
CLASS 9 FOUNDATION COURSE
CLASS 8 FOUNDATION COURSE

Please log in or register to answer this question.

1 Answer

0 votes
by (178k points)

Yes, tree traversal can be performed both recursively and iteratively. While recursive approaches are often more intuitive, iterative methods offer advantages in terms of space efficiency and can be implemented using explicit data structures like stacks or queues. Here's a brief overview of how tree traversal can be done iteratively:

Iterative Inorder Traversal:

class TreeNode:
    def __init__(self, value):
        self.val = value
        self.left = None
        self.right = None

def iterative_inorder(root):
    stack = []
    result = []

    while stack or root:
        while root:
            stack.append(root)
            root = root.left

        root = stack.pop()
        result.append(root.val)
        root = root.right

    return result
 

Iterative Preorder Traversal:

def iterative_preorder(root):
    stack = [root] if root else []
    result = []

    while stack:
        node = stack.pop()
        result.append(node.val)

        if node.right:
            stack.append(node.right)
        if node.left:
            stack.append(node.left)

    return result
 

Iterative Postorder Traversal:

def iterative_postorder(root):
    stack = [root] if root else []
    result = []

    while stack:
        node = stack.pop()
        result.insert(0, node.val)

        if node.left:
            stack.append(node.left)
        if node.right:
            stack.append(node.right)

    return result
 

These examples use a stack to simulate the recursive call stack, allowing you to traverse the tree iteratively. The key is to mimic the order of operations in a recursive traversal using a stack to keep track of the nodes to be processed.

Welcome to Sarthaks eConnect: A unique platform where students can interact with teachers/experts/students to get solutions to their queries. Students (upto class 10+2) preparing for All Government Exams, CBSE Board Exam, ICSE Board Exam, State Board Exam, JEE (Mains+Advance) and NEET can ask questions from any subject and get quick answers by subject teachers/ experts/mentors/students.

Categories

...