/114. Flatten Binary Tree to Linked List

114. Flatten Binary Tree to Linked List

Medium
Linked Lists70.3% acceptance

Given the root node of a binary tree, modify the tree in-place so that it becomes a singly linked list using the right child pointers. The left child pointers should be set to None. The linked list should follow the pre-order traversal sequence of the original tree.

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. Each node's left pointer is None, right pointer points to next.

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.

Constraints

  • 0 <= number of nodes <= 2000
  • -100 <= node value <= 100
  • The input is a valid binary tree
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(2, TreeNode(1), None)

Expected: [2, None, 1]