/114. Flatten Binary Tree to Linked List

114. Flatten Binary Tree to Linked List

Medium
Linked Lists70.3% acceptance

Given a binary tree represented by its root node, modify the tree in-place so that it becomes a singly linked list. The linked list should use the right child pointer to point to the next node, and the left child pointer should always be None. The order of nodes in the linked list must correspond to the pre-order traversal of the original binary tree. The function should not return anything; it should modify the tree in-place.

Example 1

Input: TreeNode(7, TreeNode(3, TreeNode(2), TreeNode(4)), TreeNode(8, None, TreeNode(9)))

Output: [7, None, 3, None, 2, None, 4, None, 8, None, 9]

Explanation: Pre-order traversal: 7,3,2,4,8,9. Linked list uses right pointers only.

Example 2

Input: TreeNode(10, None, TreeNode(20, TreeNode(15), None))

Output: [10, None, 20, None, 15]

Explanation: Pre-order traversal: 10,20,15.

Example 3

Input: None

Output: []

Explanation: Empty tree yields empty list.

Constraints

  • The number of nodes in the tree is in the range [0, 2000].
  • Each node's value is an integer in the range [-100, 100].
  • The input is a valid binary tree.
  • The function must modify the tree in-place and should not return anything.
Python (current runtime)

Case 1

Input: TreeNode(5, TreeNode(1), TreeNode(7, TreeNode(6), TreeNode(8)))

Expected: [5, None, 1, None, 7, None, 6, None, 8]

Case 2

Input: TreeNode(12)

Expected: [12]

Case 3

Input: TreeNode(3, TreeNode(2, TreeNode(1)), None)

Expected: [3, None, 2, None, 1]