Talentd
FleetCode

1028. Recover a Tree From Preorder Traversal

Hard83.2% acceptance6 companies

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:

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]

Constraints:

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

Hints open one at a time

Hint 1
Do an iterative depth first search, parsing dashes from the string to inform you how to link the nodes together.
19:40
Still stuck?Read 3 approaches, or watch a walkthrough.
Open solution
Loading editor…
1# Definition for a binary tree node.
2# class TreeNode:
3# def __init__(self, val=0, left=None, right=None):
4# self.val = val
5# self.left = left
6# self.right = right
7class Solution:
8 def recoverFromPreorder(self, traversal: str) -> Optional[TreeNode]:
9
Starter codePython 3Spaces: 4
Examples
Input
"1-2--3--4-5--6--7"
Input
"1-2--3---4-5--6---7"
Input
"1-401--349---90--88"
Your code is saved on this device.Solution