小黑代码(与官方题解高度一致)
"""
# 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: 'Node') -> 'Node':
if not root:
return
self.pre = None
self.head = None
# 中序遍历
def dfs(node):
if not node:
return
dfs(node.left)
# 链表转换操作
if self.pre:
node.left = self.pre
self.pre.right = node
else:
self.head = node
self.pre = node
dfs(node.right)
dfs(root)
# 首尾关联
self.head.left = self.pre
self.pre.right = self.head
return self.head
小黑生活
收到了实习公司老板的红包,开心
收到了还多小伙伴的祝福