Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit f17c5c9

Browse files
committed
O(n) time and O(n) space using queue.
1 parent 5136258 commit f17c5c9

File tree

1 file changed

+6
-8
lines changed

1 file changed

+6
-8
lines changed

700. Search in a Binary Search Tree/700. Search in a Binary Search Tree.py

Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -20,26 +20,24 @@
2020
2121
Note that an empty tree is represented by NULL, therefore you would see the expected output (serialized tree format) as [], not null.
2222
"""
23-
24-
2523
# Definition for a binary tree node.
2624
# class TreeNode:
2725
# def __init__(self, val=0, left=None, right=None):
2826
# self.val = val
2927
# self.left = left
3028
# self.right = right
3129
class Solution:
32-
def searchBST(self, root: TreeNode, val: int) -> TreeNode:
33-
if not root:
34-
return None
30+
def searchBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:
31+
if not root: return None
3532
q = collections.deque()
3633
q.append(root)
3734
while q:
3835
node = q.popleft()
3936
if node.val == val:
4037
return node
41-
if node.left:
42-
q.append(node.left)
43-
if node.right:
38+
elif node.val < val and node.right:
4439
q.append(node.right)
40+
else:
41+
if node.left:
42+
q.append(node.left)
4543
return None

0 commit comments

Comments
 (0)