思路:不论是数组还是链表,递归地找到他的root(即序列的中点),并返回。
1. 将数组转换为二叉树:
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# @param num, a list of integers
# @return a tree node
# 12:37
def sortedArrayToBST(self, num):
if not num:
return None
mid = len(num)//2 #“//”表示整数除法;“/”浮点数除法;
root = TreeNode(num[mid])
left = num[:mid]
right = num[mid+1:]
root.left = self.sortedArrayToBST(left)
root.right = self.sortedArrayToBST(right)
return root
2. 将链表转换为二叉树:
# 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):
if not head:
return None
if not head.next:
return TreeNode(head.val)
Lroot = self.find_root(head)
Troot = TreeNode(Lroot.val)
Troot.left = self.sortedListToBST(head)
Troot.right = self.sortedListToBST(Lroot.next)
return Troot
def find_root(self,head): #找到链表的中点作为后半部分的起点,并将链表切断。
if not head or not head.next:
return head
slow = head
fast = head
pre = head
while fast and fast.next:
pre = slow
slow = slow.next
fast = fast.next.next
pre.next = None
return slow