#1028
Recover a Tree From Preorder Traversal
specialist · 845 · lc hard +31 · verified · 83.2% accepted · 2,289 likes · top 95%
Description
A preorder DFS of a binary tree is encoded in the string traversal: each node is preceded by D dashes indicating its depth (root at depth 0). If a node has only one child, it is always the left child.
Given traversal, reconstruct and return the root of the binary tree.
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]
Code
1
2
3
4
5
6
7
8
9