#700
Search in a Binary Search Tree
EasyTreeBinary Search TreeBinary TreeBinary SearchTree Traversal
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(h) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(h)Space O(1)
Utilizing the properties of a binary search tree, we can efficiently find the node by comparing values and deciding which subtree to explore next.
⚙️
Algorithm
5 steps- 1Step 1: Start at the root of the tree.
- 2Step 2: Compare the current node's value with the target value.
- 3Step 3: If they match, return the current node.
- 4Step 4: If the target value is less, move to the left child; if greater, move to the right child.
- 5Step 5: Repeat until the node is found or a null reference is reached.
solution.py16 lines
1# Full working Python code
2class TreeNode:
3 def __init__(self, val=0, left=None, right=None):
4 self.val = val
5 self.left = left
6 self.right = right
7
8def searchBST(root, val):
9 while root:
10 if root.val == val:
11 return root
12 elif val < root.val:
13 root = root.left
14 else:
15 root = root.right
16 return Noneℹ
Complexity note: Here, h is the height of the tree. In a balanced tree, this is O(log n), but in the worst case (unbalanced), it can be O(n).
- 1Binary Search Trees allow for efficient searching due to their sorted nature.
- 2Understanding tree traversal methods is crucial for solving tree-related problems.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.