Practice
Solution
Step 1: Understand traversal order requirement
The problem requires visiting root before left and right subtrees, which is preorder traversal.Step 2: Identify approach with no extra space
Morris preorder traversal uses threaded binary trees to achieve preorder traversal without recursion or stack, thus optimal in space.Final Answer:
Option C -> Option CQuick Check:
Preorder visits root first; Morris traversal achieves this with O(1) space [OK]
- Confusing inorder or postorder with preorder traversal
- Assuming recursion is always needed
- Using level-order which visits nodes by depth
class Solution:
def pathSum(self, root, targetSum):
if not root:
return 0
prefix_counts = {0: 1}
result = 0
stack = [(root, 0, False)] # node, current_sum, visited_children
while stack:
node, current_sum, visited = stack.pop()
if node is None:
continue
if not visited:
current_sum += node.val
result += prefix_counts.get(current_sum - targetSum, 0)
prefix_counts[current_sum] = prefix_counts.get(current_sum, 0) + 1
stack.append((node, current_sum, True)) # Mark node as visited
stack.append((node.right, current_sum, False))
stack.append((node.left, current_sum, False))
else:
prefix_counts[current_sum] -= 1
return result
Solution
Step 1: Trace initial stack and prefix_counts
Start with stack=[(1,0,False)], prefix_counts={0:1}, result=0.Step 2: Process nodes and update result
Paths summing to 3 are: (1->2) and (3) alone, total 2 paths counted.Final Answer:
Option D -> Option DQuick Check:
Two valid paths found matching target sum [OK]
- Missing the single node path (3)
- Double counting paths due to prefix_counts not decremented
- Off-by-one in updating result
from typing import Optional
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def isSymmetric(root: Optional[TreeNode]) -> bool:
def isMirror(t1: Optional[TreeNode], t2: Optional[TreeNode]) -> bool:
if not t1 or not t2:
return t1 == t2
if t1.val != t2.val:
return False
return isMirror(t1.left, t2.right) and isMirror(t1.right, t2.left)
return isMirror(root.left, root.right) if root else True
root = TreeNode(1, TreeNode(2), TreeNode(2))
print(isSymmetric(root)) # What is the output?
Solution
Step 1: Trace isMirror on root.left and root.right nodes with value 2
Both nodes exist and have equal values, so recursion continues.Step 2: Recursively check left.left vs right.right and left.right vs right.left (both null)
Since both pairs are null, isMirror returns true for these calls, so overall returns true.Final Answer:
Option D -> Option DQuick Check:
Symmetric tree with equal child nodes returns true [OK]
- Confusing null checks causing exceptions
- Returning false prematurely on equal nodes
- Misreading recursion base cases
Solution
Step 1: Identify handling of empty tree
The code does not check if root is None before starting traversal, which can cause errors or incorrect results.Step 2: Verify other lines
Other lines handle null children safely using heights.get with default 0, and last_visited logic is correct.Final Answer:
Option A -> Option AQuick Check:
Missing early return for empty root causes bug [OK]
- Forgetting to handle empty tree as balanced
- Incorrectly comparing last_visited causing infinite loops
- Not defaulting heights for null children
Solution
Step 1: Understand traversal constraints
Without left/right child pointers, Morris traversal is not applicable since it relies on child links.Step 2: Use parent pointers to simulate traversal
By tracking current and previously visited nodes, we can move up or down the tree to simulate inorder traversal iteratively.Final Answer:
Option D -> Option DQuick Check:
Tracking previous node enables correct traversal without extra space [OK]
- Trying to create threads on parent pointers
- Using recursion without child pointers
- Confusing BFS with inorder traversal
