Recover a Tree From Preorder Traversal

HardTreesdfs

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

A binary tree was written out as a string by a pre-order traversal. For each node visited, the writer emitted D dashes, where D is the node's depth (the root has depth 0), followed immediately by the node's value. Whenever a node has exactly one child, that child is its **left** child. Given the string traversal, rebuild the tree and return its root. Values are positive integers and may have several digits, so read full numbers rather than single characters.

Examples

Input: traversal = "1-2--3--4-5--6--7"
Output: [1,2,5,3,4,6,7]
2 and 5 are at depth 1; 3 and 4 hang under 2, 6 and 7 under 5.
Input: traversal = "1-2--3---4-5--6---7"
Output: [1,2,5,3,null,6,null,4,null,7]
Each depth-2 node has a single depth-3 child, placed on the left.
Input: traversal = "1-401--349---90--88"
Output: [1,401,null,349,88,90]
401 is the root's only child; 349 and 88 are its children and 90 sits under 349.

Constraints

  • 1 <= number of nodes <= 1000
  • 1 <= Node.val <= 10^9
  • `traversal` is a valid encoding of a tree in which single children are always left children

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More dfs problems