Skip to content

700. Search in a Binary Search Tree 👍

  • Time: $O(n)$
  • Space: $O(h)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution {
 public:
  TreeNode* searchBST(TreeNode* root, int val) {
    if (root == nullptr)
      return nullptr;
    if (root->val == val)
      return root;
    if (root->val > val)
      return searchBST(root->left, val);
    return searchBST(root->right, val);
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
public class Solution {
  public TreeNode searchBST(TreeNode root, int val) {
    if (root == null)
      return null;
    if (root.val == val)
      return root;
    if (root.val > val)
      return searchBST(root.left, val);
    return searchBST(root.right, val);
  }
}
1
2
3
4
5
6
7
8
9
class Solution:
  def searchBST(self, root: TreeNode | None, val: int) -> TreeNode | None:
    if not root:
      return None
    if root.val == val:
      return root
    if root.val > val:
      return self.searchBST(root.left, val)
    return self.searchBST(root.right, val)