Flatten Binary Tree to Linked List — LeetCode 114 Python Solution
- Problem
- #114
- Pattern
- Linked List
- Reading time
- 4 min
- Source
- leetcode.com
The problem
Given the root of a binary tree, flatten the tree into a "linked list": The "linked list" should use the same TreeNode class where the right child pointer points to the next node in the list and the left child pointer is always null. The "linked list" should be in the same order as a pre-order traversal of the binary tree.
Example
- Input
- root = [1,2,5,3,4,null,6]
- Output
- [1,null,2,null,3,null,4,null,5,null,6]
Python solution
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def flatten(self, root: Optional[TreeNode]) -> None:
"""
Do not return anything, modify root in-place instead.
"""
while root:
if root.left:
pre = root.left
while pre.right:
pre = pre.right
pre.right = root.right
root.right = root.left
root.left = None
root = root.rightComplexity
| Measure | Complexity |
|---|---|
| Time | O(n), where n is the number of nodes in the tree |
| Space | O(1) auxiliary |
Pattern: Linked List
Rewire pointers in place, with a dummy head and a saved next to keep it safe. LeetCode 114. Flatten Binary Tree to Linked List is filed here because LeetCode tags it Linked List, which is the vocabulary this hub collects.
The linked list guide has the Python template for the pattern and the 75 LeetCode problems that use it.
Related problems
On a study list
This problem is on Top Interview 150.
Frequently asked questions
- How hard is LeetCode 114. Flatten Binary Tree to Linked List?
- LeetCode 114. Flatten Binary Tree to Linked List is rated Medium on LeetCode.
- What is the time complexity of LeetCode 114. Flatten Binary Tree to Linked List?
- The Python solution on this page runs in O(n), where n is the number of nodes in the tree.
- What is the space complexity of LeetCode 114. Flatten Binary Tree to Linked List?
- The Python solution on this page uses O(1) auxiliary space.
- What topics does LeetCode 114. Flatten Binary Tree to Linked List cover?
- LeetCode 114. Flatten Binary Tree to Linked List is tagged Stack, Tree, Depth-First Search, Linked List and Binary Tree on LeetCode.