题目
思路
递归构建左子树和右子树
代码
"""
Definition of ListNode
class ListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
class Solution:
"""
@param: head: The first node of linked list.
@return: a tree node
"""
def findMid(self, head):
slow = head
fast = head
pre = ListNode(0)
pre.next = head
while fast and fast.next:
pre = pre.next
slow = slow.next
fast = fast.next.next
pre.next = None
return slow
def sortedListToBST(self, head):
# write your code here
if not head: return None
mid = self.findMid(head)
root = TreeNode(mid.val)
if head == mid: return root
root.left = self.sortedListToBST(head)
root.right = self.sortedListToBST(mid.next)
return root