"""
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
class Solution:
"""
@param root: a TreeNode, the root of the binary tree
@return: nothing
"""
def flatten(self, root):
# write your code here
if root is None:
return None
l = []
self.pre_oder(root,l) #先前序遍历 吧所有数据保存
t = root #把一个指针指向root,说着说,和root指向同一个地址,保证不另开辟空间
for i in range(1,len(l)): #因为已经指向root,所以从1开始索引
t2 = TreeNode(l[i])
t.left = None
t.right = t2
t = t.right # 每次把指针移到右侧
return root
def pre_oder(self,root,l):
if root is None:
return None
l.append(root.val)
self.pre_oder(root.left,l)
self.pre_oder(root.right,l)
将一棵二叉树按照前序遍历拆解成为一个假链表
。所谓的假链表是说,用二叉树的 right 指针,来表示链表中的 next指针。
样例
1
\
1 2
/ \ \
2 5 => 3
/ \ \ \
3 4 6 4
\
5
\
6
挑战
不使用额外的空间耗费。
注意事项
不要忘记将左儿子标记为 null,否则你可能会得到空间溢出或是时间溢出。