边工作边刷题:70天一遍leetcode: day 17-1
Convert Sorted List to Binary Search Tree
只能顺序访问链表结点,所以不能像array那样preorder的方式建树。而是inorder,因为inorder的顺序和有序的。
- 每次访问完左子树,这时候的head指向的是当前的root。这时再移动链表指针。
- 因为python是pass-by-value,而recursion的返回值为子树的root,所以只能用global variable表示当前指针(如果c++可以用pass-by-reference update链表指针)
# 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 sortedListToBST(self, head):
"""
:type head: ListNode
:rtype: TreeNode
"""
self.h = head
n = 0
while head:
n+=1
head=head.next
return self.sorteddfs(0, n-1)
def sorteddfs(self, low, high):
if low>high: return None
m = low+(high-low)/2
left = self.sorteddfs(low, m-1)
root = TreeNode(self.h.val)
if self.h: self.h = self.h.next
right = self.sorteddfs(m+1, high)
root.left = left
root.right = right
return root