oneby7

Binary Trees Depth first: return a value up

365. Flatten Binary Tree to Linked List

Medium

You are given root, the root node of a binary tree. Flatten the tree into a linked list. The list is made of the same nodes: each node's right pointer points to the next node of the list, and its left pointer is null. Your function returns nothing: it changes the tree in place.

The nodes appear in the list in preorder. Preorder lists a node before the nodes below it. It starts with the root, then lists the root's whole left subtree in preorder, and then its whole right subtree in preorder.

The judge walks the right pointers from the root. If a node on the way is not one of the nodes you were given, or still has a left child, the output names the first such node, counting the root as node 1, in place of the tree.

The examples write a tree level by level, from left to right, with null where a child is missing. So root = [5,8,null,3] is the root 5 with a left child 8 and no right child, and 8 has a left child 3. The missing children after the last node are left out. The output shows the tree after your function returns, written the same way, so a flattened tree reads [1,null,2,null,3].

Example 1

6931428

Input: root = [4, 9, 2, 6, 1, null, 8, null, null, 3]

Output: [4,null,9,null,6,null,1,null,3,null,2,null,8]

Explanation: In preorder the root 4 comes first, then its left subtree: 9, 6, 1 and 1's child 3. The right subtree comes last: 2, then 8. Each node points right to the next one, and every left pointer is null.

Example 2

Input: root = []

Output: []

Explanation: The tree has no nodes, so there is nothing to change.

Example 3

10⁹−10⁹-2

Input: root = [-2, -1000000000, null, 1000000000]

Output: [-2,null,-1000000000,null,1000000000]

Explanation: The tree is a path down the left side. Flattened, the same three nodes form a path down the right side, in the same order.

Check your understanding

Work out the answer for this input before you write any code.

root = [8, 3, 5, null, 7, 6]

Constraints

  • 0 ≤ number of nodes ≤ 105
  • -109 ≤ Node.val ≤ 109
  • The tree has at most 1000 levels.

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.