Skip to the code
cf.
+10 XP

#362 Write a Layout as Text

easy

Your editor saves its split-pane layout to localStorage as one string. The format is a preorder walk (node, left subtree, right subtree) where each node writes its value, each missing child writes #, and items are separated by commas.

Write writeLayout(root) that returns that string. For example, a root 1 with only a left child 2 is written 1,2,#,#,#. An empty tree is written #.

Example 1

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

After 2 come its two empty children, then 1's right subtree.

Example 2

Input: root = []
Output: "#"

An empty tree is a single #.

Constraints

  • 0 <= number of nodes <= 10^4
  • 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).