Skip to content

Latest commit

 

History

History
27 lines (25 loc) · 678 Bytes

convert-sorted-array-to-binary-search-tree.md

File metadata and controls

27 lines (25 loc) · 678 Bytes

Convert Sorted Array to 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):
        if len(num) == 0:
            return None
        if len(num) == 1:
            return TreeNode(num[0])
        mid = len(num) / 2
        root = TreeNode(num[mid])
        left = self.sortedArrayToBST(num[:mid])
        right = self.sortedArrayToBST(num[mid+1:])
        root.left = left
        root.right = right
        return root