0%

leetcode题解114:二叉树展开为链表

描述

该题来自于力扣第114题

分析

用递归简单很多,假设已经有一个函数可以将以root为根结点的树转为链表,记该函数为func(root),显然现处理左子树func(root.left)和右子树func(root.right),这时左右子树已经变为链表了,然后就简单多了,模拟下过程,分为三步:
1. 将左子树的最右结点指向右子树的根结点
2. root.right = root.left
3. root.left = null

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution:
def flatten(self, root: Optional[TreeNode]) -> None:
"""
Do not return anything, modify root in-place instead.
"""
if root:
self.flatten(root.left)
self.flatten(root.right)
if root.left:
left_last = root.left
while left_last.right:
left_last = left_last.right
left_last.right = root.right
root.right = root.left
root.left = None