思路
思路:使用列表存儲先序遍歷的相關節點。然后遍歷列表,分別獲取前驅節點和當前節點,將前驅節點的左指針指向空,前驅節點的右指針指向當前節點。
# 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: Optional[TreeNode]) -> None:"""Do not return anything, modify root in-place instead."""#先序遍歷 root.left root.rightres=[]def preorder(node):if not node:return res.append(node)preorder(node.left)preorder(node.right)preorder(root)for i in range(1,len(res)):pre,cur=res[i-1],res[i]pre.left=Nonepre.right=cur