"""
给定一个二叉树,原地将它展开为链表。
例如,给定二叉树
1
/ \
2 5
/ \ \
3 4 6
将其展开为:
1
\
2
\
3
\
4
\
5
\
6
"""
def flatten(root):
def helper(root):
if root is None:
return
helper(root.left)
helper(root.right)
if root.left:
pre = root.left # 使用了辅助变量
while pre.right:
pre = pre.right
pre.right = root.right
root.right = root.left
root.left = None
helper(root)
def flatten2(root):
while root:
if root.left:
most_right = root.left
while most_right.right:
most_right = most_right.right
most_right.right = root.right
root.right = root.left
root.left = None
root = root.right
return
114_二叉树展开为链表
最新推荐文章于 2023-05-24 16:00:17 发布