leetcode 将已排序的 数组/链表 转换为二叉搜索树(BST),Python实现

来源:互联网 发布:java.swing包 编辑:程序博客网 时间:2024/05/16 19:44

思路:不论是数组还是链表,递归地找到他的root(即序列的中点),并返回。

1. 将数组转换为二叉树:

# Definition for a binary tree node.# class TreeNode(object):#     def __init__(self, x):#         self.val = x#         self.left = None#         self.right = Noneclass 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 = Noneclass 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


阅读全文
0 0
原创粉丝点击