Start learning free

LESSON 505 OF 679 · BINARY TREES

Flatten Binary Tree

Practice O(n)

You get the root of a binary tree. Rearrange it in place into one chain of nodes that only goes right:

  • Keep the same nodes. Each node's right child becomes the next node of the chain.
  • Every left child becomes None.
  • The chain holds the nodes in preorder. That is a node first, then its left subtree, then its right subtree.

Your function returns nothing. The tests follow the right children from root and print what they find.

 

Example 1:

Input: root = [3,1,5,None,2,4]
Output: [3,None,1,None,2,None,5,None,4]
       3
      / \
     /   \
    1     5
     \   /
      2 4

Explanation: After flattening, the nodes form one chain in preorder:
3 → 1 → 2 → 5 → 4
Each arrow points to a right child.
No node has a left child.

Example 2:

Input: root = [2,1]
Output: [2,None,1]
Explanation: 1 was the left child of 2.
Now it is the right child.

 

Constraints:

  • The tree has 1 to 1,000 nodes.
  • Each value is a whole number from 1 to 1,000.
  • All values are different.
STEP 1 OF 9
    Ctrl + Enter to check