diff options
| author | terminaldweller <thabogre@gmail.com> | 2022-08-10 04:23:05 +0000 | 
|---|---|---|
| committer | terminaldweller <thabogre@gmail.com> | 2022-08-10 04:23:05 +0000 | 
| commit | 2bcfccd3540b84144fc534b1b7e657dbd29fab52 (patch) | |
| tree | 3e41095bdea32a0b6cd9bfd86c0153e32808171b /108 | |
| parent | update (diff) | |
| download | leetcode-2bcfccd3540b84144fc534b1b7e657dbd29fab52.tar.gz leetcode-2bcfccd3540b84144fc534b1b7e657dbd29fab52.zip  | |
update
Diffstat (limited to '')
| -rwxr-xr-x | 108/main.py | 36 | 
1 files changed, 36 insertions, 0 deletions
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()  | 
