Given a binary tree, flatten it to a linked list in-place.
For example, given the following tree:
1
/ \
2 5
/ \ \
3 4 6
The flattened tree should look like:
1
\
2
\
3
\
4
\
5
\
6
My code:
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def flatten(self, root):
"""
:type root: TreeNode
:rtype: None Do not return anything, modify root in-place instead.
"""
if root==None:
return root
root0=root
value_list=[]
value_list=self.Left_first(root,value_list)
print(value_list)
for i,value in enumerate(value_list):
if i==0:
continue
treenode=TreeNode(value)
root0.right=treenode
root0.left=None
root0=treenode
def Left_first(self,root,value_list):
if root==None:
return None
value_list.append(root.val)
left=root.left
self.Left_first(left,value_list)
right=root.right
self.Left_first(right,value_list)
return value_list
Solution: https://leetcode.com/problems/flatten-binary-tree-to-linked-list/