lintcode练习-106. Convert Sorted List to Binary Search Tree

106. Convert Sorted List to Binary Search Tree

给出一个所有元素以升序排序的单链表,将它转换成一棵高度平衡的二分查找树

样例

               2
1->2->3  =>   / \
             1   3

实现思路:

如样例给出的一样,平衡二叉树要左右对齐,所以我们可以以中心结点为根结点,对左右部分进行递归建树。

"""
Definition of ListNode
class ListNode(object):

    def __init__(self, val, next=None):
        self.val = val
        self.next = next

Definition of TreeNode:
class TreeNode:
    def __init__(self, val):
        self.val = val
        self.left, self.right = None, None
"""


class Solution:
    """
    @param: head: The first node of linked list.
    @return: a tree node
    """
    def sortedListToBST(self, head):
        # write your code here
        if head is None:
            return None
        
        return self.helper(head)
    
    def helper(self,head):
        if head.next is None:
            return TreeNode(head.val)
        
        if head.next.next is None:
            root = TreeNode(head.val)
            root.left = None
            root.right = TreeNode(head.next.val)
            return root
        
        #获取中心指针和中心指针的前一个指针
        mid_pre, mid = self.findPreMid(head)
        root = TreeNode(mid.val)
        
        #递归中心指针右半部分
        root.right = self.helper(mid.next)
        # 移除中心指针和右半部分,就获得了左半部分
        mid_pre.next = None
        #递归中心指针左半部分
        root.left = self.helper(head)

        return root
        
    def findPreMid(self, head):
        slow, fast = head, head.next
        slow_pre = slow
        #利用快慢指针,获取中心指针
        while fast != None and fast.next != None:
            slow_pre = slow
            fast = fast.next.next
            slow = slow.next
        
        return slow_pre, slow

精简版本

#精简版本
class Solution:
    """
    @param: head: The first node of linked list.
    @return: a tree node
    """
    def sortedListToBST(self, head):
        # write your code here        
        if head is None:
            return None
        if head.next is None:
            return TreeNode(head.val)
        
        slow, fast = head, head.next
        while fast.next and fast.next.next:
            slow = slow.next
            fast = fast.next.next
        
        mid = slow.next
        slow.next = None
        
        root = TreeNode(mid.val)
        root.left = self.sortedListToBST(head)
        root.right = self.sortedListToBST(mid.next)
        return root

猜你喜欢

转载自blog.csdn.net/qq_36387683/article/details/81709637