Practice
prev after the call flatten(root) completes?Solution
Step 1: Trace flatten calls on root=1
flatten(1) calls flatten(3) then flatten(2). After flatten(3), prev=TreeNode with val=3; after flatten(2), prev=TreeNode with val=2; finally, root=1 sets root.right=prev (2) and prev=TreeNode with val=1.Step 2: Final value of prev after flatten(1)
After processing root=1, prev points to the root node with val=1.Final Answer:
Option B -> Option BQuick Check:
Global prev ends at root node after full traversal [OK]
- Assuming prev ends at last leaf node
- Confusing order of recursive calls
- Forgetting prev is updated after rewiring
Solution
Step 1: Analyze main loops
The algorithm iterates preorder once, pushing and popping nodes from stack at most once each.Step 2: Consider hash map lookups
Hash map lookups for inorder indices are O(1) each, so no extra log factor.Final Answer:
Option C -> Option CQuick Check:
Each node processed once with O(1) operations [OK]
- Assuming nested loops cause O(n^2)
- Confusing hash map lookup cost
- Counting recursion stack space in iterative approach
Solution
Step 1: Understand the problem change
The tree is no longer complete, so properties used by optimal methods do not hold.Step 2: Identify correct counting method
Only a full traversal (DFS or BFS) guarantees counting all nodes correctly in O(n) time.Final Answer:
Option D -> Option DQuick Check:
Optimal methods rely on completeness, which is lost here [OK]
- Trying to apply binary search on last level
- Assuming height checks still reduce complexity
Solution
Step 1: Identify problem with deep recursion
Recursive DFS can cause stack overflow on very deep trees.Step 2: Use iterative BFS with null markers
Iterative BFS avoids recursion stack issues and null markers preserve structure even with duplicates.Step 3: Avoid assumptions about uniqueness or balanced shape
Duplicates require storing all nodes explicitly; balanced assumptions break correctness.Final Answer:
Option A -> Option AQuick Check:
Iterative BFS with null markers handles deep trees and duplicates safely [OK]
- Removing null markers to save space breaks reconstruction
- Using recursion on deep trees causes stack overflow
- Assuming unique values or balanced trees
Solution
Step 1: Understand the variant ignores node values, only structure matters
Therefore, the value comparison step must be removed to avoid false negatives due to duplicates.Step 2: Modify the DFS to only check if both nodes exist or are null, recursively comparing mirrored subtrees
Return true if both nodes are null; otherwise, recurse on mirrored children without comparing values.Final Answer:
Option C -> Option CQuick Check:
Ignoring values means skipping value checks but preserving mirrored structure checks [OK]
- Keeping value checks causing false negatives
- Using BFS palindrome checks which fail on structure
- Using preorder traversal which ignores mirrored structure
