Bird
Raised Fist0

What is the space complexity of the optimal in-place flatten algorithm that uses reverse preorder traversal with a global pointer on a binary tree of n nodes and height h?

medium🪤 Complexity Trap Q13 of Q15
Tree: Depth-First Search - Flatten Binary Tree to Linked List
What is the space complexity of the optimal in-place flatten algorithm that uses reverse preorder traversal with a global pointer on a binary tree of n nodes and height h?
AO(n) due to storing all nodes in a list during traversal
BO(1) because the algorithm modifies the tree in-place without extra memory
CO(log n) because the tree height is always balanced and recursion stack is limited
DO(h) due to recursion stack depth in worst case of skewed tree
Step-by-Step Solution
Solution:
  1. Step 1: Identify auxiliary space usage

    The algorithm uses recursion, so space is dominated by recursion stack depth, which is the tree height h.
  2. Step 2: Clarify why O(h) not O(1) or O(n)

    It does not store nodes externally (not O(n)) and is not constant space due to recursion stack (not O(1)). For skewed trees, h can be up to n.
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    Recursion stack space equals tree height h [OK]
Quick Trick: Recursion stack space equals tree height h [OK]
Common Mistakes:
MISTAKES
  • Assuming O(1) space because of in-place modification
  • Confusing recursion stack with explicit data structures
  • Assuming balanced tree always so O(log n) space
Trap Explanation:
PITFALL
  • Option C looks correct because of in-place rewiring, but recursion stack uses O(h) space. Option D assumes balanced tree which is not guaranteed.
Interviewer Note:
CONTEXT
  • Tests understanding of recursion stack space vs explicit auxiliary space.
Master "Flatten Binary Tree to Linked List" in Tree: Depth-First Search

3 interactive learning modes - each teaches the same concept differently

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Tree: Depth-First Search Quizzes