Recover a Tree From Preorder Traversal

We run a preorder depth-first search (DFS) on the root of a binary tree.

At each node in this traversal, we output D dashes, where D is the depth of this node, then we output the value of this node. If the depth of a node is D, the depth of its immediate child is D + 1. The depth of the root node is 0.

If a node has only one child, that child is guaranteed to be the left child.

Given the output traversal of this traversal, recover the tree and return its root.

Example 1
        1
       / \
      2   5
     / \ / \
    3  4 6  7
Inputtraversal = "1-2--3--4-5--6--7"
Output[1,2,5,3,4,6,7]
The preorder traversal string reconstructs the binary tree with root 1, children 2 and 5, and grandchildren 3, 4, 6, and 7.
Example 2
        1
       / \
      2   5
     /   /
    3   6
   /   /
  4   7
Inputtraversal = "1-2--3---4-5--6---7"
Output[1,2,5,3,null,6,null,4,null,7]
The depths encoded by the dashes reconstruct the tree whose level-order representation is [1,2,5,3,null,6,null,4,null,7].

Constraints

  • The number of nodes in the original tree is in the range [1, 1000].
  • 1 <= Node.val <= 10^9

Asked at 5 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate