Practice
Solution
Step 1: Understand the problem constraints
The problem requires checking balance at every node efficiently without recomputing heights multiple times.Step 2: Identify the approach that avoids redundant work
Postorder traversal that returns both height and balance status in one pass allows early exit on imbalance and avoids repeated height calculations.Final Answer:
Option D -> Option DQuick Check:
Postorder traversal with early exit is O(n) and avoids recomputation [OK]
- Checking balance only at root misses subtree imbalances
- Computing height separately for each node causes O(n²) time
- Using BFS to check balance is incorrect as balance depends on subtree heights
Solution
Step 1: Analyze predecessor visits
Each node's left subtree is traversed to find the predecessor, which can take up to h steps where h is the height of the tree.Step 2: Count total operations
In skewed trees, this leads to O(n x h) time complexity due to repeated traversal of left subtrees.Final Answer:
Option B -> Option BQuick Check:
Worst-case time complexity is O(n x h) [OK]
- Assuming predecessor search is O(1) per node
- Confusing threading effect with total complexity
- Ignoring skewed tree worst case
Solution
Step 1: Analyze height and binary search
Height h = O(log n). Binary search on last level does O(log n) steps.Step 2: Combine existence checks
Each existence check traverses height h = O(log n). Total time = O(log n) * O(log n) = O((log n)^2).Final Answer:
Option C -> Option CQuick Check:
Nested log factors from height and binary search [OK]
- Confusing O(log n) with O((log n)^2)
- Assuming linear time due to traversal
Solution
Step 1: Understand rob_current calculation
rob_current should be node.val plus the not_rob values of left and right children, because robbing current node forbids robbing immediate children.Step 2: Identify the bug
Line 5 incorrectly adds left[0] and right[0] (rob values of children), violating adjacency constraint.Final Answer:
Option A -> Option AQuick Check:
Using rob values of children overcounts and breaks correctness [OK]
- Mixing rob and not_rob indices in tuple
- Forgetting adjacency constraints
def hasPathSum(root: Optional[TreeNode], targetSum: int) -> bool:
def dfs(node, curr_sum):
if not node:
return False
curr_sum += node.val
if curr_sum == targetSum: # Bug here
return True
return dfs(node.left, curr_sum) or dfs(node.right, curr_sum)
return dfs(root, 0)
Solution
Step 1: Understand leaf node condition
The sum should be checked only at leaf nodes, not at every node.Step 2: Identify the bug
Line 6 checks sum at any node, causing premature True returns for partial paths.Final Answer:
Option B -> Option BQuick Check:
Bug causes incorrect True if partial path sum equals targetSum [OK]
- Checking sum at internal nodes
- Not handling null root
