Skip to main content

🌳 Trees

Trees are everywhere: file systems, ASTs, DBs, the DOM. ~90% of tree problems are "do DFS or BFS and return something". Once you fluently translate problems into traversal + accumulator, this category collapses.

This category contains 77 problems. Use the patterns below to recognize what's being asked, then jump to the problem list at the bottom.


🧠 Key Patterns​

  • DFS (recursive) β€” Most natural for trees. Pre/In/Post-order. Return a value per subtree.
  • BFS (queue) β€” Level-order, shortest path in tree, populating-next pointers.
  • BST Property β€” Left < root < right. In-order traversal yields sorted output.
  • LCA β€” Lowest Common Ancestor: recursion returning subtree containment.
  • Serialize / Deserialize β€” Pre-order with null markers; or level-order BFS.
  • Path Problems β€” Path sum, diameter, max gain β€” return "best ending here" + update global.

⚠️ Common Pitfalls​

  • Stack overflow on skewed trees β€” consider iterative when depth > 10⁴.
  • Forgetting to handle null children in recursion.
  • Mutating a global accumulator without resetting between test cases.

πŸ“š Study Resources​

πŸ“Ί Videos​

πŸ“– Books​

  • Introduction to Algorithms (CLRS) β€” Ch. 12 (BST), Ch. 13 (Red-Black)
  • Algorithm Design Manual β€” Skiena β€” Ch. 3.4

🌐 Articles & References​


πŸ’» All Trees Problems​