knaxuslearn · build · ship

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.

  1. 48Pow(x, n) (opens LeetCode in a new tab)Recursion that halves the problemMedium
    Common mistake
    Calling pow twice instead of storing half.
  2. 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.
  3. 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.
  4. 51Invert Binary Tree (opens LeetCode in a new tab)Recursion that changes the treeEasy
    Common mistake
    Forgetting to return the node.
  5. 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)).
  6. 53Diameter of Binary Tree (opens LeetCode in a new tab)Return height, track a global bestEasycore
    Common mistake
    Returning the diameter where the height is needed, or the other way round.
  7. 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.
  8. 55Validate Binary Search Tree (opens LeetCode in a new tab)Carry valid boundsMediumcore
    Common mistake
    Comparing only with the parent, which misses deeper violations.
  9. 56Lowest Common Ancestor of a Binary Search Tree (opens LeetCode in a new tab)Use BST orderingMediumcore
    Common mistake
    Equal values: the node itself can be p or q.
  10. 57Kth Smallest Element in a BST (opens LeetCode in a new tab)Inorder traversalMediumcore
    Common mistake
    A counter that is not shared across recursive calls.