# 114 flatten binary tree to linked list

### 114. Flatten Binary Tree to Linked List

Medium

class Solution(object):
def flatten(self, root):
"""
:type root: TreeNode
:rtype: void Do not return anything, modify root in-place instead.
"""
def preorder(root):
res = []
if not root:
return res
res.append(root)
if root.left:
res.extend(preorder(root.left))
if root.right:
res.extend(preorder(root.right))
return res
if not root:
return
node_order = preorder(root)
for i in range(len(node_order)-1):
node_order[i].left = None
node_order[i].right = node_order[i+1]
node_order[-1].left = None
node_order[-1].right = None


beat 40.67%

class Solution(object):
def flatten(self, root):
"""
:type root: TreeNode
:rtype: void Do not return anything, modify root in-place instead.
"""
if not root:
return
left_node = root.left
right_node = root.right
root.left = None
self.flatten(left_node)
self.flatten(right_node)
if left_node:
root.right = left_node
while left_node.right:
left_node = left_node.right
left_node.right = right_node


beat 32.18%

apachecn/AiLearning