Engrain by ByteRush

DSA.10.01 Mid-levelCore — asked often

Pattern 11: Tree DFS

Comes up in: DSA

This concept is being written. It gets the full five steps — explanation, predict, interview angle, practice with tests, and review cards. Here is exactly what it will cover, so you can study it elsewhere in the meantime.

What it covers

  • recursive DFS returning values up
  • passing state down
  • global answer vs return value (diameter)
  • iterative DFS with a stack
  • serialisation

Words you will know

depth-first searchpost-order aggregation

What you will practise

  • max-depth (E)
  • invert-tree (E)
  • balanced-tree (E)
  • diameter (E)
  • path-sum (E)
  • same-tree (E)
  • subtree-of-another (E)
  • lowest-common-ancestor (M)
  • serialize-deserialize (H)

Interview questions this answers

  • Find the maximum depth of a binary tree recursively and iteratively.
  • What is the difference between DFS and BFS? When do you use each?
  • Find the lowest common ancestor of two nodes.
  • Serialize and deserialize a binary tree.