Leetcode 114, Flatten Binary Tree to Linked List

时间:2021-08-04 08:57:25

根据提示,本题等价于pre order traverse遍历,并且依次把所有的节点都存成right child,并把left child定义成空集。用递归的思想,那么如果分别把左右子树flatten成list,我们有:

1

/    \

2     5

\       \

3      6 <- rightTail

\

4  <- leftTail

所以使用递归的解法一: 注意由于右子树最后要接到左子树的后面,所以用temp保存右子树的head。

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