-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsearch-in-a-binary-search-tree.py
More file actions
38 lines (32 loc) · 1014 Bytes
/
Copy pathsearch-in-a-binary-search-tree.py
File metadata and controls
38 lines (32 loc) · 1014 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
from typing import 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:
# Time complexity: O(log n)
# Space complexity: O(1)
# Iterative
def searchBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:
while root:
if root.val == val:
return root
elif root.val < val:
root = root.right
else:
root = root.left
return root
# Time complexity: O(log n)
# Space complexity: O(log n)
# Recursive
def searchBST2(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:
if not root:
return None
if root.val == val:
return root
if root.val < val:
return self.searchBST(root.right, val)
else:
return self.searchBST(root.left, val)