Examples:
2
None
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
def search_BST(root: Optional[TreeNode], val: int) -> Optional[TreeNode]:
while root:
if root.val == val:
return root
elif root.val < val:
# go right
root = root.right
else:
root = root.left
return root
We can run an example as follows:
root = TreeNode(4)
root.left = TreeNode(2)
root.right = TreeNode(6)
root.left.left = TreeNode(1)
root.left.right = TreeNode(3)
root.right.left = TreeNode(5)
root.right.right = TreeNode(7)
search_BST(root,2).val
## 2
And another example:
## True
The time complexity of this solution is \(O(H)\), where \(H\) is the height of the tree. In a balanced binary search tree we would have had \(O(logn)\), since \(H = log(n)\). However, the worst case scanrio (one-way sided tree) time complexity will be \(O(N)\).