diff --git a/invert-binary-tree/ppxyn1.py b/invert-binary-tree/ppxyn1.py new file mode 100644 index 0000000000..57da1f79c6 --- /dev/null +++ b/invert-binary-tree/ppxyn1.py @@ -0,0 +1,24 @@ +# 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 + +# idea : dfs +# Time Complexity : O(n) + +class Solution: + def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]: + if root is None: + return None + + tmp = root.left + root.left = root.right + root.right = tmp + + self.invertTree(root.left) + self.invertTree(root.right) + return root + + diff --git a/search-in-rotated-sorted-array/ppxyn1.py b/search-in-rotated-sorted-array/ppxyn1.py new file mode 100644 index 0000000000..be93bb55d0 --- /dev/null +++ b/search-in-rotated-sorted-array/ppxyn1.py @@ -0,0 +1,30 @@ +# idea : binary search +# Time Complexity : O(log n) + +# Sorting is not allowed because it costs O(n log n), so we must handle it using binary search without sorting. +# One way is to check where the sorted order is disrupted. + +class Solution: + def search(self, nums: List[int], target: int) -> int: + left, right = 0, len(nums)-1 + + while left <= right: + mid = (left + right) // 2 + + if nums[mid] == target: + return mid + + if nums[left] <= nums[mid]: + if nums[left] <= target < nums[mid]: + right = mid - 1 + else: + left = mid + 1 + + else: + if nums[mid] < target <= nums[right]: + left = mid + 1 + else: + right = mid - 1 + return -1 + +