Skip to the code
cf.
+25 XP

#363 Read a Layout Back From Text

medium

When the editor starts, it reads the saved layout string back. The format is a preorder walk: each node is its value, each missing child is #, and items are separated by commas. For example, 1,2,#,#,# is a root 1 with a left child 2.

Write readLayout(text) that rebuilds the tree and returns its root (null for #). The text is always valid.

Example 1

Input: text = "1,2,#,#,3,4,#,#,5,#,#"
Output: [1,2,3,null,null,4,5]

1 takes 2,#,# as its left subtree and the rest as its right subtree.

Example 2

Input: text = "#"
Output: []

A single # is an empty tree.

Constraints

  • 1 <= text.length <= 10^5
  • Values are whole numbers, possibly negative.

Trees are written level by level, like [1, 2, 3, null, 4], where null is a missing child. Your function works with TreeNode objects, each with val, left, and right.

Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).