Bird
Raised Fist0
DSA Pythonprogramming~5 mins

Morris Traversal Inorder Without Stack in DSA Python - Time & Space Complexity

Choose your learning style10 modes available
Time Complexity: Morris Traversal Inorder Without Stack
O(n)
Understanding Time Complexity

We want to understand how the Morris Traversal method for inorder tree traversal performs as the tree size grows.

Specifically, how many steps does it take to visit all nodes without using extra memory for a stack?

Scenario Under Consideration

Analyze the time complexity of the following Morris Inorder Traversal code.


def morris_inorder(root):
    current = root
    while current:
        if not current.left:
            print(current.val)
            current = current.right
        else:
            pre = current.left
            while pre.right and pre.right != current:
                pre = pre.right
            if not pre.right:
                pre.right = current
                current = current.left
            else:
                pre.right = None
                print(current.val)
                current = current.right

This code visits all nodes of a binary tree in inorder without using a stack or recursion by temporarily modifying pointers.

Identify Repeating Operations

Look for loops and repeated steps in the code.

  • Primary operation: The outer while loop runs as long as there is a current node.
  • Nested operation: The inner while loop finds the rightmost node in the left subtree (predecessor).
  • How many times: Each edge in the tree is visited at most twice because the traversal creates and removes temporary links.
How Execution Grows With Input

As the number of nodes (n) increases, the traversal visits each node and its edges a limited number of times.

Input Size (n)Approx. Operations
10About 20 visits (nodes and edges)
100About 200 visits
1000About 2000 visits

Pattern observation: The number of operations grows roughly twice the number of nodes, so it grows linearly.

Final Time Complexity

Time Complexity: O(n)

This means the traversal time grows directly in proportion to the number of nodes in the tree.

Common Mistake

[X] Wrong: "Because of the nested while loop, the time complexity must be O(n²)."

[OK] Correct: The inner loop does not run fully for every node; it only moves along edges that are visited at most twice, keeping total work linear.

Interview Connect

Understanding Morris Traversal shows you can traverse trees efficiently without extra memory, a skill that impresses by combining clever pointer use and time efficiency.

Self-Check

"What if we used recursion instead of Morris Traversal? How would the time and space complexity change?"

Practice

(1/5)
1. What is the main advantage of Morris Traversal for inorder tree traversal compared to the traditional recursive or stack-based methods?
easy
A. It uses no extra space for stack or recursion.
B. It is faster than all other traversal methods.
C. It only works on binary search trees.
D. It modifies the tree permanently.

Solution

  1. Step 1: Understand Morris Traversal space usage

    Morris Traversal uses threaded binary trees to avoid recursion or stack, so it uses O(1) extra space.
  2. Step 2: Compare with other methods

    Traditional inorder traversal uses recursion or stack which requires O(h) space, where h is tree height.
  3. Final Answer:

    It uses no extra space for stack or recursion. -> Option A
  4. Quick Check:

    Space complexity = O(1) [OK]
Hint: Morris uses threads, no stack or recursion needed [OK]
Common Mistakes:
  • Thinking Morris is faster in time complexity
  • Believing it only works on BSTs
  • Assuming it permanently changes the tree
2. Which of the following code snippets correctly initializes the current node for Morris inorder traversal in Python?
easy
A. current = root
B. current = None
C. current = root.left
D. current = root.right

Solution

  1. Step 1: Identify starting point for traversal

    Morris traversal starts from the root node to cover the entire tree.
  2. Step 2: Check initialization options

    Setting current = root ensures traversal begins at the tree's root.
  3. Final Answer:

    current = root -> Option A
  4. Quick Check:

    Start at root node [OK]
Hint: Always start traversal from root node [OK]
Common Mistakes:
  • Starting from None causes no traversal
  • Starting from root.left misses root node
  • Starting from root.right misses left subtree
3. What will be the output of the Morris inorder traversal on the following binary tree?

    2
   / \
  1   3
Assuming the traversal prints node values in order.
medium
A. [2, 1, 3]
B. [1, 3, 2]
C. [3, 2, 1]
D. [1, 2, 3]

Solution

  1. Step 1: Understand inorder traversal order

    Inorder traversal visits left subtree, root, then right subtree.
  2. Step 2: Apply Morris traversal order

    For the tree, left is 1, root is 2, right is 3, so output is [1, 2, 3].
  3. Final Answer:

    [1, 2, 3] -> Option D
  4. Quick Check:

    Inorder = left-root-right = [1, 2, 3] [OK]
Hint: Inorder = left, root, right always [OK]
Common Mistakes:
  • Confusing preorder or postorder with inorder
  • Misreading tree structure
  • Assuming traversal prints in insertion order
4. Consider this snippet of Morris inorder traversal code in Python:

current = root
while current:
    if current.left is None:
        print(current.val)
        current = current.right
    else:
        pre = current.left
        while pre.right and pre.right != current:
            pre = pre.right
        if pre.right is None:
            pre.right = current
            current = current.left
        else:
            pre.right = None
            print(current.val)
            current = current.right
What is the main bug if the line pre.right = None is missing?
medium
A. The traversal will print nodes in preorder instead of inorder.
B. The traversal will skip the root node.
C. The traversal will enter an infinite loop.
D. The traversal will cause a syntax error.

Solution

  1. Step 1: Understand role of pre.right = None

    This line removes the temporary thread created to return to the root after left subtree traversal.
  2. Step 2: Consequence of missing this line

    If not removed, the thread remains, causing the loop to revisit nodes endlessly, creating an infinite loop.
  3. Final Answer:

    The traversal will enter an infinite loop. -> Option C
  4. Quick Check:

    Missing thread removal = infinite loop [OK]
Hint: Always remove temporary threads to avoid loops [OK]
Common Mistakes:
  • Thinking it causes syntax error
  • Assuming it changes traversal order
  • Believing it skips nodes
5. You want to modify Morris inorder traversal to collect node values in a list instead of printing them. Which of the following code changes correctly achieves this without changing the traversal logic?

result = []
current = root
while current:
    if current.left is None:
        # Change here
        current = current.right
    else:
        pre = current.left
        while pre.right and pre.right != current:
            pre = pre.right
        if pre.right is None:
            pre.right = current
            current = current.left
        else:
            pre.right = None
            # Change here
            current = current.right
hard
A. Replace only second '# Change here' line with result.append(current.val)
B. Replace both '# Change here' lines with result.append(current.val)
C. Replace only first '# Change here' line with result.append(current.val)
D. Replace both '# Change here' lines with print(current.val)

Solution

  1. Step 1: Identify where nodes are visited

    In Morris traversal, nodes are visited and printed in two places: when left is None and after removing thread.
  2. Step 2: Replace print with appending to list

    To collect values, replace both print statements with result.append(current.val) to capture all visited nodes.
  3. Final Answer:

    Replace both '# Change here' lines with result.append(current.val) -> Option B
  4. Quick Check:

    Collect all visited nodes in list [OK]
Hint: Append values at both visit points to collect all nodes [OK]
Common Mistakes:
  • Appending only once misses some nodes
  • Leaving print statements causes unwanted output
  • Changing traversal logic breaks correctness
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard