递归,就像汉诺塔一样,挺神奇的,虽然不知道内部咋做的,但我知道最后一步的做法。
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def flatten(self, root: TreeNode) -> None:
"""
Do not return anything, modify root in-place instead.
"""
if not root: return
self.flatten(root.left) # 将左子树拉直
self.flatten(root.right) # 将右子树拉直
left = root.left
right = root.right # 备份
root.right = left # 左子树接到右子树的位置上
root.left = None # 原本的左子树位置置为None
while(root.right):
root = root.right # 找到右子树的最后
root.right = right # 拼接上去