-
Notifications
You must be signed in to change notification settings - Fork 2
/
700.py
36 lines (31 loc) · 890 Bytes
/
700.py
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
# [ LeetCode ] 700. Search in a Binary Search Tree
class TreeNode:
def __init__(
self,
val: int = 0,
left: "TreeNode" | None = None,
right: "TreeNode" | None = None
):
self.val = val
self.left = left
self.right = right
def solution(root: TreeNode, val: int) -> TreeNode | None:
stack: list[TreeNode] = [root]
while stack:
node: TreeNode = stack.pop()
if node.val == val:
return node
if node.right:
stack.append(node.right)
if node.left:
stack.append(node.left)
return None
def another_solution(root: TreeNode, val: int) -> TreeNode | None:
while root:
if root.val > val:
root = root.left
elif root.val < val:
root = root.right
else:
return root
return None