-
Notifications
You must be signed in to change notification settings - Fork 80
/
search_in_a_binary_search_tree.py
47 lines (38 loc) · 1.27 KB
/
search_in_a_binary_search_tree.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
37
38
39
40
41
42
43
44
45
46
47
# coding: utf-8
"""
https://leetcode.com/problems/search-in-a-binary-search-tree/
"""
class TreeNode: # pragma: no cover
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def searchBST(self, root: TreeNode, val: int) -> TreeNode:
if not root:
return root
def search_node(node, value):
node_val = node.val
if value == node_val:
return node
elif value < node_val:
if node.left:
return search_node(node.left, value)
elif value > node_val:
if node.right:
return search_node(node.right, value)
return None
return search_node(root, val)
class Solution2:
def searchBST(self, root: TreeNode, val: int) -> TreeNode:
def search_node(node, value):
if not node:
return None
node_val = node.val
if value == node_val:
return node
elif value < node_val:
return search_node(node.left, value)
elif value > node_val:
return search_node(node.right, value)
return search_node(root, val)