Convert Sorted Array to Binary Search Tree @ LeetCode (Python)
Triangle @ LeetCode (Python)

Convert Sorted List to Binary Search Tree @ LeetCode (Python)

kitt posted @ 2014年3月07日 21:15 in LeetCode , 2281 阅读

先把链表转成数组,再递归。每次数组的中点元素为root, 再递归地建立左右子树。

# 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 sortedListToBST(self, head):
        num = []; curr = head
        while curr != None: 
            num.append(curr.val)
            curr = curr.next
        return self.createBST(num, 0, len(num) - 1)
        
    def createBST(self, num, start, end):
        if start > end: return None
        mid = (start + end) / 2
        root = TreeNode(num[mid])
        root.left = self.createBST(num, start, mid - 1)
        root.right = self.createBST(num, mid + 1, end)
        return root

登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter