[leetcode]Convert Sorted List to Binary Search Tree @ Python

原題地址:http://oj.leetcode.com/problems/convert-sorted-list-to-binary-search-tree/html

題意:將一條排序好的鏈表轉換爲二叉查找樹,二叉查找樹須要平衡。node

解題思路:兩個思路:一,可使用快慢指針來找到中間的那個節點,而後將這個節點做爲樹根,並分別遞歸這個節點左右兩邊的鏈表產生左右子樹,這樣的好處是不須要使用額外的空間,壞處是代碼不夠整潔。二,將排序好的鏈表的每一個節點的值存入一個數組中,這樣就和http://www.cnblogs.com/zuoyuan/p/3722103.html這道題同樣了,代碼也比較整潔。數組

代碼:app

# Definition for a  binary tree node
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
#
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    # @param head, a list node
    # @return a tree node
    def sortedArrayToBST(self, array):
        length = len(array)
        if length==0: return None
        if length==1: return TreeNode(array[0])
        root = TreeNode(array[length/2])
        root.left = self.sortedArrayToBST(array[:length/2])
        root.right = self.sortedArrayToBST(array[length/2+1:])
        return root
        
    def sortedListToBST(self, head):
        array = []
        p = head
        while p:
            array.append(p.val)
            p = p.next
        return self.sortedArrayToBST(array)
        
相關文章
相關標籤/搜索