CodingNodes / Trees / Flatten Binary Tree to Linked List System design Space play · ←→ step · R restart

Problem

Rearrange a binary tree in place so that it turns into a "linked list" that goes down the right side: every node's left pointer becomes null, and its right pointer points to the next node in preorder (node, then left subtree, then right subtree).

The function returns nothing; it changes the tree it is given. The tree is given in level order with null for a missing child, and the answer is the same tree read back in level order after the call.

Constraints

  • 0 ≤ number of nodes ≤ 2000
  • -100 ≤ Node.val ≤ 100
  • Reuse the existing nodes; do not build a new tree

Examples: pick one to animate

Solutions

TimeO(n) SpaceO(1)

Time: Like a Morris traversal, the walks that look for pred only follow right pointers, and over the whole run every pointer is followed a constant number of times.

Space: Only the cur and pred pointers are used, and the tree is rewired in place.

For a node with a left subtree, the last node of that subtree (always going right) must be followed by the node's right subtree. Hang the right subtree under that last node, move the left subtree to the right, clear the left pointer, and step to the right. Repeat until the right chain ends.