Flatten Binary Tree to Linked List

Medium#114pre-order

You get the root of a binary tree. Turn it, in place, into a list along the right links: every left link becomes none, and following right from the root gives the nodes in pre-order. Our tree: 4 with children 8 and 2; 8 has children 1 and 6; 2 has a left child, 5 — the answer is 4 → 8 → 1 → 6 → 2 → 5.

input
root: a binary tree, written as on LeetCode: its values level by level, left to right, null for a missing child.
returns
Nothing: relink the tree's own nodes in place into a «linked list» in preorder, each node's right the next one and its left null. The tests write the tree from the root given: [1, null, 2, null, 3].
constraints
  • 0 ≤ the number of nodes ≤ 1000
  • −100 ≤ Node.val ≤ 100
our 12 tests keep to them
examples
Open a test in the tests panel: it shows the input and the expected answer.
/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {void} Do not return anything, modify root in-place instead.
 */
function flatten(root) {

}
Ctrl ↵
format
reset

saved in this browser

12 tests · limit 3 s

Stuck?

See the solution run step by step on our example, then why it works and its complexity.

Watch the walkthrough →

Next: more tree traversals problems

Pattern “Tree traversals” →

The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.