"""
# Definition for a Node.
class Node:
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
"""
class Solution:
def treeToDoublyList(self, root: 'Optional[Node]') -> 'Optional[Node]':
head=None
last=None
def _dfs(root):
nonlocal head, last
if not root:return
_dfs(root.left)
if not head:
head=root
if last:
last.right=root
root.left=last
last=root
_dfs(root.right)
_dfs(root)
if not head:return head
head.left=last
last.right=head
return head
注意这个写法维护两个指针