Question Link:
https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/
Same idea to Convert Sorted List to Binary Search Tree, but we use a recursive function to construct the binary search tree.
[-]
Python code accepted by LeetCode OJ
# Definition for a binary tree node
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# @param num, a list of integers
# @return a tree node
def sortedArrayToBST(self, num):
n = len(num)
if n == 0:
return None
elif n == 1:
return TreeNode(num[0])
mid = n / 2
root = TreeNode(num[mid])
root.left = self.sortedArrayToBST(num[:mid])
root.right = self.sortedArrayToBST(num[mid+1:])
return root