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


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

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

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

代碼:

# 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)
        

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM