From 2bcfccd3540b84144fc534b1b7e657dbd29fab52 Mon Sep 17 00:00:00 2001 From: terminaldweller Date: Wed, 10 Aug 2022 08:53:05 +0430 Subject: update --- 108/main.py | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100755 108/main.py diff --git a/108/main.py b/108/main.py new file mode 100755 index 0000000..2872178 --- /dev/null +++ b/108/main.py @@ -0,0 +1,36 @@ +#!/usr/bin/env python3 +# https://yellowcoding.com/leetcode-108-convert-sorted-array-to-binary-search-tree/ + +from typing import List, Optional + +# Definition for a binary tree node. +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: List[int]) -> Optional[TreeNode]: + def fun(nums: List[int], low: int, high: int): + if low > high: + return None + + mid: int = int((low + high) / 2) + node = TreeNode(val=nums[mid]) + node.left = fun(nums, low, mid - 1) + node.right = fun(nums, mid + 1, high) + return node + + return fun(nums, 0, len(nums) - 1) + + +def main(): + solution = Solution() + print(solution.sortedArrayToBST([-10, -3, 0, 5, 9])) + print(solution.sortedArrayToBST([1, 3])) + + +if __name__ == "__main__": + main() -- cgit v1.2.3