private TreeNode tree(ListNode b, ListNode e){ if (b == e) returnnull; ListNode fast = b; ListNode slow = b; while (fast.next != e && fast.next.next != e) { fast = fast.next.next; slow = slow.next; } TreeNode root = new TreeNode(slow.val); root.left = tree(b, slow); root.right = tree(slow.next, e); return root; } }
Python 强行和官方答案匹配。
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next # 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 classSolution: defsortedListToBST(self, head: ListNode) -> TreeNode:
deftree(head, end): if head == end: returnNone
fast = slow = head
while fast.next != end: fast, slow = fast.next, slow.next if fast.next != end: fast = fast.next
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next # 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 classSolution: defsortedListToBST(self, head: ListNode) -> TreeNode: self.head, n = head, 0 while head: head = head.next n += 1
defdfs(b, e): if b >= e: returnNone m = b + e >> 1 left = dfs(b, m) root = TreeNode(self.head.val, left) self.head = self.head.next root.right = dfs(m + 1, e) return root