PIXELBANKv9.1.0
Menu

Flatten Binary Tree to Linked List

Flatten a binary tree to a linked list in-place using preorder traversal. Each node's left becomes null, right points to next preorder node.

Input: level-order array. Output: values in flattened order, space-separated.

Example:

Input:
1,2,5,3,4,null,6
Output:
1 2 3 4 5 6
Reasoning:
  • The binary tree is constructed from the level-order array: root node 1, left child 2, right child 5, left child of 2 is 3, right child of 2 is 4, and right child of 5 is 6.
  • The tree is then traversed in preorder (root, left, right), resulting in the order: 1, 2, 3, 4, 5, 6.
  • During the traversal, each node's left child is set to null and its right child is set to the next node in the preorder sequence, effectively flattening the tree into a linked list.
  • The final output is the values of the nodes in the flattened linked list, in order, separated by spaces: 1 2 3 4 5 6.

Constraints:

  • 0 <= number of nodes <= 2000
  • -100 <= Node.val <= 100
🔒

Editor locked

The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.

solution.py

Test Results

0/0
Run code to see test results.
Flatten Binary Tree to Linked List - Medium | PixelBank