Skip to main content

114. Flatten Binary Tree to Linked List

https://leetcode.com/problems/flatten-binary-tree-to-linked-list

Python

class Solution:
def flatten(self, root: Optional[TreeNode]) -> None:
if root is None:
return None

# 1. Flattern both sub-trees
self.flatten(root.left)
self.flatten(root.right)

# 2. Left subtree as right tree
origin_left = root.left
origin_right = root.right

root.left = None
root.right = origin_left

# 3. Attach origin right tree to the eof right tree
cur = root
while cur.right:
cur = cur.right
cur.right = origin_right