1. 程式人生 > >leetcode 將已排序的 陣列/連結串列 轉換為二叉搜尋樹(BST),Python實現

leetcode 將已排序的 陣列/連結串列 轉換為二叉搜尋樹(BST),Python實現

思路:不論是陣列還是連結串列,遞迴地找到他的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