# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def __init__(self):
self.cur=None
def sortedListToBST(self, head):
"""
:type head: ListNode
:rtype: TreeNode
"""
self.cur=head
n=self.getSize(head)
return self.bStree(n)
def getSize(self,head):
n=0
while head:
n+=1
head=head.next
return n
def bStree(self,n):
if n<=0:
return None
l=self.bStree(n/2)
root=TreeNode(self.cur.val)
self.cur=self.cur.next
r=self.bStree(n-n/2-1)
root.left=l
root.right=r
return root
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def __init__(self):
self.cur=None
def sortedListToBST(self, head):
"""
:type head: ListNode
:rtype: TreeNode
"""
self.cur=head
n=self.getSize(head)
return self.bStree(n)
def getSize(self,head):
n=0
while head:
n+=1
head=head.next
return n
def bStree(self,n):
if n<=0:
return None
l=self.bStree(n/2)
root=TreeNode(self.cur.val)
self.cur=self.cur.next
r=self.bStree(n-n/2-1)
root.left=l
root.right=r
return root