【LeetCode OJ】Convert Sorted Array to Binary Search Tree

时间:2024-04-11 14:05:17

Problem Link:

http://oj.leetcode.com/problems/convert-sorted-array-to-binary-search-tree/

Same idea to Convert Sorted Array to Binary Search Tree, but we use a recursive function to construct the binary search tree.

# 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