22 · Tree Recursion

#114 Flatten Binary Tree to Linked List

Mediumsolve on LeetCode ↗

frequently reported atMicrosoftAmazonMetaGoogle

the problem

In plain words

Rewire a binary tree in place into a "linked list" made of the same TreeNode objects: each node's right pointer goes to the next node in preorder, and every left pointer becomes null. The method returns nothing.

in root = [1,2,5,3,4,null,6]

out [1,null,2,null,3,null,4,null,5,null,6]

Preorder is 1, 2, 3, 4, 5, 6.

in root = []

out []

in root = [0]

out [0]

  • 0 ≤ number of nodes ≤ 2000
  • -100 ≤ Node.val ≤ 100
  • Follow-up: O(1) extra space

your turn

Try it before you peek

Read the examples, say the brute force out loud, then write code: here or on LeetCode ↗. Stuck for 20 minutes? Open one hint at a time.

Solve it in the browser

LeetCode-style: complete the class. Compiled by the real javac (Java 17) and judged right here — nothing is sent anywhere.

    Solutions are hidden so you can try first. Even 20 minutes of real effort makes the answer stick far better than reading it.

    Marking the problem solved, or opening every hint, also shows it.

    practise next

    Similar problems

    1. #206
      Reverse Linked List
      Easyin Linked Lists
    2. #117
    3. #226
      Invert Binary Tree
      Easyin Tree Recursion