Skip to the code
+25 XP

#321 Flatten a Layout Into a Chain

medium

A screen reader reads the panes of a layout in preorder: a pane, then everything in its left part, then everything in its right part. To make that easy, you want to turn the tree into a single chain in that order.

Write flattenLayout(root) that changes the tree in place: after it runs, every node's left is null, and following right pointers from the root visits the nodes in preorder. The function doesn't need to return anything.

Example 1

Input: root = [4,2,7,1,3]
Output: [4,null,2,null,1,null,3,null,7]

Preorder is 4, 2, 1, 3, 7, now linked by right pointers.

Example 2

Input: root = [1,null,2]
Output: [1,null,2]

It is already a chain.

Constraints

  • 0 <= number of nodes <= 10^5
  • The tree is at most 3000 levels deep.

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 big inputs that check your code is fast enough, and solves the problem when they all pass.

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