思路
思路:使用列表存储先序遍历的相关节点。然后遍历列表,分别获取前驱节点和当前节点,将前驱节点的左指针指向空,前驱节点的右指针指向当前节点。
# 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