Skip to content

Commit

Permalink
solution(python): 108. Convert Sorted Array to Binary Search Tree
Browse files Browse the repository at this point in the history
108. Convert Sorted Array to Binary Search Tree
  • Loading branch information
godkingjay authored Oct 10, 2023
2 parents f2ecab7 + 95ed1b9 commit 1c86d9e
Showing 1 changed file with 22 additions and 0 deletions.
22 changes: 22 additions & 0 deletions Easy/108. Convert Sorted Array to Binary Search Tree/Solution.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right

class Solution:
def sortedArrayToBST(self, nums):
if not nums:
return None
head = self.helper(nums, 0, len(nums) - 1)
return head

def helper(self, nums, low, high):
if low > high:
return None
mid = low + (high - low) // 2
node = TreeNode(nums[mid])
node.left = self.helper(nums, low, mid - 1)
node.right = self.helper(nums, mid + 1, high)
return node

0 comments on commit 1c86d9e

Please sign in to comment.