Ctrl K

Tree Into a Right Chain

Medium
You are given the root of a binary tree. Rebuild it into a chain made of the same nodes: - every node's left link is None; - the right link points to the next node of the chain, and the last node's is None; - the nodes follow preorder: a node first, then its left subtree, then its right subtree. Rewire the existing nodes rather than creating new ones, and return the head of the chain — the old root (None for an empty tree). Can you do it with O(1) extra memory?
Example 1
root=tree_node([7, 3, 9, 1, None, None, 4]) → [7, None, 3, None, 1, None, 9, None, 4]

The preorder is 7, 3, 1, 9, 4. After the call the tree is the chain 7 → 3 → 1 → 9 → 4 along right links, with every left link None.

Example 2
root=tree_node([5, 2, None, -6]) → [5, None, 2, None, -6]

The tree leans left: 5 → 2 → -6. The nodes move to the right side, giving the chain 5 → 2 → -6.

Example 3
root=tree_node([]) → None

An empty tree: nothing to change.

Constraints
  • 0 ≤ number of nodes ≤ 2000
  • -100 ≤ Node.val ≤ 100
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsTree From Bracket Notation MediumPair Across Two Search Trees MediumChain Down the Tree MediumListing in Preorder MediumLeft, Node, Right Easy
loading Python…
Input
root=tree_node([7, 3, 9, 1, None, None, 4])
Expected
[7, None, 3, None, 1, None, 9, None, 4]

Run checks the first 3 tests in your browser. Submit checks all 34 tests on the server, hidden ones included.