思路一
把该树进行前序遍历,然后再连接起来。
class Solution:
def flatten(self, root: TreeNode) -> None:
"""
Do not return anything, modify root in-place instead.
"""
res = []
if not root:
return root
def helper(root):
if not root:
return
res.append(root.val)
helper(root.left)
helper(root.right)
helper(root)
size = len(res)
for i in range(1, size):
pre, cur = res[i - 1], res[i]
pre.left = None
pre.right = cur
思路二
递归
def flatten(self, root: TreeNode, pre = None) -> None:
"""
Do not return anything, modify root in-place instead.
"""
# 类似后序遍历
def helper(root, pre):
if not root: return pre
# 记录遍历时候,该节点的前一个节点
pre = helper(root.right, pre)
pre = helper(root.left, pre)
# 拼接
root.right = pre
root.left = None
pre = root
return pre
helper(root, None)