PPractick

DSA interview question

All Root-to-Leaf Paths

Medium · Data structures · Topics: tree, dfs, backtracking

The problem

A decision-tree debugger lists every path from the root to a leaf, like "1->2->5", so analysts can see each complete chain of decisions. A DFS carries the path built so far. At a leaf it records the finished path; otherwise it extends the path with the child and recurses. Passing the path by value (or appending and then undoing) keeps sibling branches from seeing each other's nodes.

Example: [1, 2, 3, null, 5] → ["1->2->5", "1->3"].

Function signature

vector<string> binaryTreePaths(TreeNode* root);  // leaf paths from left to right

Test cases

Input (level order)OutputExplanation
[1, 2, 3, null, 5]["1->2->5", "1->3"]
[1, 2, 3, 4, 5, 6, 7]["1->2->4", "1->2->5", "1->3->6", "1->3->7"]
[1, null, 2, null, 3]["1->2->3"]One leaf
[1]["1"]The root is a leaf
[][]

(Confirm: a leaf has no children; paths are listed in left-to-right order of their leaves.)

How interviewers phrase it

Clarifying questions to ask

  1. What output format? (Strings like "1->2->5", or lists of values.)
  2. Does a single node count as a path? (Yes.)
  3. Can values be negative? (Yes, which only matters for formatting.)

Follow-ups to expect

  1. "Why is it important to check for a leaf, not null?"
  2. "Pass by value or backtrack?"
  3. "How many paths can there be?"
  4. "Related problems?"
  5. "Complexity?"

Practise questions like this with a real engineer

On Practick another engineer interviews you live for 60 minutes on a question from this bank. They have the full interviewer guide beside the call: the expected answer to every follow-up, hints to give if you stall, and a scoring rubric. You get the model solution once the session settles. It is free: interview someone for an hour and you have earned your own.

Book a free mock interview

Related questions

All 474 dsa interview questions

DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in