tree
dfs
bfs
]
Leetcode 0700. Search in a Binary Search Tree
https://leetcode.com/problems/search-in-a-binary-search-tree
This is exercise to undertand what is Binary Search Tree and how it works. Remember, that left subtree is always lesser than root and right subtree is always bigger than root. So, what we need to do? We start from the root of our tree and compare value in its root. If value we are looking is less than value in root, we go left, if it is more, we go to the right. When we stop? Either if we found place, where these two values are equal, or we reached NULL leaf (it means we visited leaf and descended to its NULL children). In this cases we save found node to global variable, which we return in the end.
Complexity, both time and space is O(h)
, where h
is heigth of our tree.
Remark: I used helper
function, which is not necessary here, but in this way the code is more universal for different trees traversal problems, where you need to return more difficult objects.
class Solution:
def helper(self, root):
if not root or root.val == self.val:
self.Found = root
return root
if root.val < self.val:
return self.helper(root.right)
if root.val > self.val:
return self.helper(root.left)
def searchBST(self, root, val):
self.val = val
self.Found = None
self.helper(root)
return self.Found
If you like the solution, you can upvote it on leetcode discussion section: Problem 0700