Logo
IconChallenge
Icon
IconProblem
IconSolutions
IconSubmissions

Recover a Tree From Preorder Traversal

XPChallenge Points: 30
levelLevel: Hard

You’re given a preorder DFS of a binary tree encoded as a string.
For each node, the encoding writes D dashes (where D is the node’s depth, with root depth 0) followed by the node’s integer value. If a node has only one child, it’s guaranteed to be the left child.
Reconstruct the binary tree and return its root.

Example 1:

Input: traversal = "1-2--3--4-5--6--7"

Output: [1,2,5,3,4,6,7]

Example 2:

Input: traversal = "1-2--3---4-5--6---7"

Output: [1,2,5,3,null,6,null,4,null,7]

Example 3:

Input: traversal = "1-401--349---90--88"

Output: [1,401,null,349,88,90]

to Continue
like
dislike

Accepted:

Submission:

IconReport an issue
Icon
IconCode
IconYou need toto run or submitYou need toto run or submit
IconTest Case
IconTest Result