class Solution:
def sortedArrayToBST(self, nums: List[int]) -> Optional[TreeNode]:
if not nums:
return None
mid = len(nums) // 2
root = TreeNode(val=nums[mid])
root.left = self.sortedArrayToBST(nums[:mid])
root.right = self.sortedArrayToBST(nums[mid+1:])
return root
# 中序,记录前一个pre, 以及根节点first
class Solution:
def __init__(self):
self.first = None
self.pre = None
def treeToDoublyList(self, root):
self.dfs(root)
self.first.left = self.pre # 循环链表, dfs后最后一位正是self.pre
self.pre.right = self.first
return self.first
def dfs(self, root):
if not root:
return
self.dfs(root.left)
if not self.first: # 记录首位
self.first = root
if self.pre: # 遍历过程中,一直记录前一位. 每一轮进行指针更新
root.left = self.pre
self.pre.right = root
self.pre = root
self.dfs(root.right)