Flatten Binary Tree to Linked List
MediumTrees
Decode it first. Clues, constraints, pattern and plan before any code.Given the root of a binary tree, flatten it in place into a "linked list" made of the same nodes:
- every node's
leftbecomes empty, and - following
rightpointers from the root visits the nodes in preorder (node, then left subtree, then right subtree).
Do not return anything. The tests walk the right pointers from the original root after your function runs.
Trees in the examples are written in level order (top to bottom, left to right), with null for a missing child, the same way the tests build them.
[1, 2, 5, 3, 4, null, 6] → 1 -> 2 -> 3 -> 4 -> 5 -> 6 (all left pointers empty)
[] → nothing to do
[0] → 0Follow-up: can you do it with O(1) extra space?
Constraints
0 <= number of nodes <= 2000-100 <= Node.val <= 100