week 6 of 15
Recursion and tree DFS
Get comfortable with these coding mechanics first: a function that calls itself, a base case, what the function returns, passing state as a parameter, a TreeNode with left and right. Template to type from memory by the end of the week: say in one sentence what the function returns. Base case, recurse on children, combine.
- 48Pow(x, n) (opens LeetCode in a new tab)Recursion that halves the problemMedium
- Common mistake
- Calling pow twice instead of storing half.
- 49Climbing Stairs (opens LeetCode in a new tab)Recursion, then memo, then loopEasy
- Common mistake
- Missing the base cases for n = 1 and n = 2.
- 50Maximum Depth of Binary Tree (opens LeetCode in a new tab)Recursion that returns a valueEasy
- Common mistake
- Counting nodes versus edges when a tree is empty.
- 51Invert Binary Tree (opens LeetCode in a new tab)Recursion that changes the treeEasy
- Common mistake
- Forgetting to return the node.
- 52Balanced Binary Tree (opens LeetCode in a new tab)Return a height, or a failure valueEasy
- Common mistake
- Recomputing heights at every node (O(n^2)).
- 53Diameter of Binary Tree (opens LeetCode in a new tab)Return height, track a global bestEasy
- Common mistake
- Returning the diameter where the height is needed, or the other way round.
- 54Count Good Nodes in Binary Tree (opens LeetCode in a new tab)Recursion that carries a parameterMedium
- Common mistake
- Using a global for the max instead of a parameter.
- 55Validate Binary Search Tree (opens LeetCode in a new tab)Carry valid boundsMedium
- Common mistake
- Comparing only with the parent, which misses deeper violations.
- 56Lowest Common Ancestor of a Binary Search Tree (opens LeetCode in a new tab)Use BST orderingMedium
- Common mistake
- Equal values: the node itself can be p or q.
- 57Kth Smallest Element in a BST (opens LeetCode in a new tab)Inorder traversalMedium
- Common mistake
- A counter that is not shared across recursive calls.